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").
Iterate trough reverse list?
How do I use reverse list in Python to loop through a list backwards? - Ask a Question - TestMu AI Community
python - Reverse list using for loop - Stack Overflow
Differences in iteration through a loop in reverse order - Python
Videos
To get a new reversed list, apply the reversed function and collect the items into a list:
>>> xs = [0, 10, 20, 40]
>>> list(reversed(xs))
[40, 20, 10, 0]
To iterate backwards through a list:
>>> xs = [0, 10, 20, 40]
>>> for x in reversed(xs):
... print(x)
40
20
10
0
>>> xs = [0, 10, 20, 40]
>>> xs[::-1]
[40, 20, 10, 0]
Extended slice syntax is explained here. See also, documentation.
Hello - why is this code not working an i get an error:
l = [1,2,3] for i in l.reverse(): print(i)
and i get this error
Traceback (most recent call last):
File "C:\Users\Polzi\Documents\DEV\Python-Private\temp1.py", line 7, in <module>
for i in l.reverse():
TypeError: 'NoneType' object is not iterable
(NormalScraping) Only this code is working:
l = [1,2,3] l.reverse() for i in l: print(i)
Why is the first code not working?
#use list slicing
a = [123,122,56,754,56]
print(a[::-1])
List can be reversed using for loop as follows:
>>> def reverse_list(nums):
... # Traverse [n-1, -1) , in the opposite direction.
... for i in range(len(nums)-1, -1, -1):
... yield nums[i]
...
>>>
>>> print list(reverse_list([1,2,3,4,5,6,7]))
[7, 6, 5, 4, 3, 2, 1]
>>>
Checkout this link on Python List Reversal for more details