Iterate over a sequence in reverse order in python

By: Python Documentation Team  

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

Archived Comments

1. Brettkip
View Tutorial          By: Brettkip at 2017-06-05 08:26:17

Most Viewed Articles (in Python )

Latest Articles (in Python)

Comment on this tutorial