Iterate over a sequence in reverse order in python

By: Python Documentation Team Viewed: 192 times  Printer Friendly Format    


Use the reversed() built-in function, which is new in Python 2.4:

for x in reversed(sequence):
    ... # do something with x...


This won’t touch your original sequence, but build a new copy with reversed order to iterate over.

With Python 2.3, you can use an extended slice syntax:

for x in sequence[::-1]:
    ... # do something with x...



Most Viewed Articles (in Python )

Latest Articles (in Python)

Comment on this tutorial