(An Unofficial) Python FAQ Wiki

putting the community back in "maintained by the community"

How do I iterate over a sequence in reverse order?

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:
        <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>

CATEGORY: programming

Comments

Python 2.4 adds the reversed() built-in.