Iterating over sequence in reversed order
Use built-in function reversed()
to iterate over a sequence in reversed order.
>>> l = [1, 2, 3, 4, 5]
>>> for i in reversed(l):
... print(i)
...
5
4
3
2
1
The reverse iteration will only work if the object has a certain size or if a special __reversed__() method is implemented in it. If
none of these conditions are met, you will have to convert the object to a list first. For example:
# Prints lines in the file in reversed order
with open('somefile.txt') as f:
for line in reversed(list(f)):
print(line)
Note that converting an iterated object into a list can consume a lot of memory if the list is large.