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.
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.
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").
How can I search backwards through a list without actually reversing the list order?
Why does [::-1] reverse a list?
Videos
Hi all. I'm trying to figure out a way to search for a specific value starting at the end of a list and moving backwards. I also need the index of that value, so reversing the list won't work because that will change all of the indexes around.
Example:
numbers = [2, 5, 6, 9, 4, 6, 3, 5]
I also want to ignore the occurrence of the desired value if it's the last number in the list, so if 5 is the number in question, I need to be able to skip past the last 5 and get index 1 from the above list, since 5 last appeared at that index, ignoring the very last 5.
Thanks!
Why would a double colon reverse a list? Is this something we just have to accept or is there some logic?
a = ['corge', 'quux', 'qux', 'baz', 'bar', 'foo'] print(a[::-1])