Nov 10, 2014

How do I iterate over a sequence in reverse order?

If it is a list, the fastest solution is 

for x in list:
"do something with x"

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[:]
for x in rev:
<do something with x>

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]
<do something with x>

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):
<do something with x>

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]:
<do something with x>


Post a Comment