Wednesday 25 April 2012

How do I iterate over a sequence in reverse order? | Python

If it is a list, the fastest solution is
list.reverse()
try:
for x in list:
"do something with x"
finally:
list.reverse()
This has the disadvantage that while you are in the loop, the list is temporarily reversed. If you don't like this, you can make a copy. This appears expensive but is actually faster than other solutions:
rev = list[:]
rev.reverse()
for x in rev:

If it's not a list, a more general but slower solution is:
for i in range(len(sequence)-1, -1, -1): x = sequence[i]

A more elegant solution, is to define a class which acts as a sequence and yields the elements in reverse order (solution due to Steve Majewski):
class Rev:
def __init__(self, seq): self.forw = seq
def __len__(self):
return len(self.forw)
def __getitem__(self, i):
return self.forw[-(i + 1)]
You can now simply write:
for x in Rev(list):

Unfortunately, this solution is slowest of all, due to the method call overhead. With Python 2.3, you can use an extended slice syntax:
for x in sequence[::-1]: