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.
Use the reversed() Function to Traverse a List in Reverse Order in Python. We can traverse a list in Python in reverse order by using the inbuilt reversed() function available. The reversed() function returns the reversed iteration of the sequence provided as input.
Python comes with a number of methods and functions that allow you to reverse a list, either directly or by iterating over the list object. You'll learn how to reverse a Python list by using the reversed() function, the . reverse() method, list indexing, for loops, list comprehensions, and the slice method.
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").
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With