Alex Rivera | Logout

Traverse a list in reverse order in Python

Asked 2009-02-09T19:04:58.527
1118

How do I traverse a list in reverse order in Python? So I can start from collection[len(collection)-1] and end in collection[0].

I also want to be able to access the loop index.

Edit
Report

1 Answer

44

The reversed builtin function is handy:

for item in reversed(sequence):

The documentation for reversed explains its limitations.

For the cases where I have to walk a sequence in reverse along with the index (e.g. for in-place modifications changing the sequence length), I have this function defined an my codeutil module:

from six.moves import zip as izip, range as xrange

def reversed_enumerate(sequence):
    return izip(
        reversed(xrange(len(sequence))),
        reversed(sequence),
    )

This one avoids creating a copy of the sequence. Obviously, the reversed limitations still apply.

answered 2011-10-11T06:28:19.650

Your Answer