Joan Venge Joan Venge - 11 days ago 6
Python Question

Traverse a list in reverse order in Python

So I can start from

len(collection)
and end in
collection[0]
.

EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.

Answer

Use the reversed() built-in function:

>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
...     print i
... 
baz
bar
foo

To also access the original index:

>>> for i, e in reversed(list(enumerate(a))):
...     print i, e
... 
2 baz
1 bar
0 foo