How to make a reverse for loop in python?

Gary Herron gherron at islandtraining.com
Sat Sep 20 12:37:42 EDT 2008


Alex Snast 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)
> --
> http://mail.python.org/mailman/listinfo/python-list
>   

What are you trying to loop through?

If it's the contents of a list, you can reverse the list (in place) first:

L = [1,2,3]
L.reverse()
for item in L:
  print item

Or you can create a new reversed (copy of the original) list and iterate 
through it

for item in reversed(L):
  print item

If it's just a sequence of numbers you want to generate:

range(3)  generates a forward list [0,1,2], and
range(3,0,-1) generates a backward list [2,1,0]

so

for i in range(11,0,-1):

might be what you want.


If your list is huge, consider xrange rather than range.


And as always, you could just roll your own index manipulation:

i = 10
while i >=0:
  # do whatever
  i -= 1




Gary Herron





More information about the Python-list mailing list