How do I iterate over a sequence in reverse order?
Python 2.4 and later has a built-in reversed iterator, which takes an arbitrary sequence, and iterates over it backwards:
for x in reversed(L): print x # do something with x
For earlier versions, it’s usually fastest to simply reverse the list during the loop:
L.reverse() try: for x in L: print x # do something with x finally: L.reverse()
This has the disadvantage that while you are in the loop, the list is temporarily reversed. If this is a problem, you can make a copy instead:
rev = L[:] rev.reverse() for x in rev: print x # do something with x
Note that both reverse and the copy operation only copies object references, so they’re a lot faster than they may appear (performance depends on the number of items in the list, not the size of those items).
If the sequence is not a list, but supports extended slicing, you can do:
for x in sequence[::-1]: print x # do something with x
For arbitrary sequences, you can do:
for i in xrange(len(sequence)-1, -1, -1): x = sequence[i] print x # do something with x
Finally, you can define your own version of 2.4’s reversed:
class Reversed: def __init__(self, seq): self.seq = seq def __len__(self): return len(self.seq) def __getitem__(self, i): return self.seq[-(i + 1)] for x in Reversed(sequence): print x # do something with x
However, this solution is slower than the other examples shown here, due to the method call overhead.
