How to make a reverse for loop in python?

Duncan Booth duncan.booth at invalid.invalid
Sat Sep 20 12:32:43 EDT 2008


Alex Snast <asnast at gmail.com> wrote:

> Hello
> 
> I'm new to python and i can't figure out how to write a reverse for
> loop in python
> 
> e.g. the python equivalent to the c++ loop
> 
> for (i = 10; i >= 0; --i)
> 

The exact equivalent would be:

    	for i in range(10, -1, -1): print i

except you virtually never want to do that in Python. Don't expect just to 
translate statement by statement from one language to another: normally in 
Python you will iterate directly over the sequence you want to process 
rather than trying to count loop indices with all the telegraph pole errors 
that result.

The usual way to iterate over a sequence in reverse is:

   for x in reversed(seq): print x

although if you know it is a list, string or other object that supports 
extended slicing you can also do:

    for x in seq[::-1]: print x

this may be less clear than using 'reversed', but does allow you to specify 
an explicit start, stop and step if you want to do only part of the 
sequence.



More information about the Python-list mailing list