Traverse a list in reverse order in Python


Question

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.

1
618
3/3/2017 3:24:40 PM

Accepted Answer

Use the built-in reversed() function:

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

To also access the original index, use enumerate() on your list before passing it to reversed():

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

Since enumerate() returns a generator and generators can't be reversed, you need to convert it to a list first.

1028
4/9/2019 3:34:47 AM

You can do:

for item in my_list[::-1]:
    print item

(Or whatever you want to do in the for loop.)

The [::-1] slice reverses the list in the for loop (but won't actually modify your list "permanently").


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon