patternpythonCritical
Traverse a list in reverse order in Python
Viewed 0 times
listorderpythontraversereverse
Problem
How do I traverse a list in reverse order in Python? So I can start from
I also want to be able to access the loop index.
collection[len(collection)-1] and end in collection[0].I also want to be able to access the loop index.
Solution
Use the built-in
To also access the original index, use
Since
reversed() function:>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
... print(i)
...
baz
bar
fooTo 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 fooSince
enumerate() returns a generator and generators can't be reversed, you need to convert it to a list first.Code Snippets
>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
... print(i)
...
baz
bar
foo>>> for i, e in reversed(list(enumerate(a))):
... print(i, e)
...
2 baz
1 bar
0 fooContext
Stack Overflow Q#529424, score: 1824
Revisions (0)
No revisions yet.