Fix Python – How to loop backwards in python? [duplicate]

Question

Asked By – snakile

I’m talking about doing something like:

for(i=n; i>=1; --i) {
   //do something with i
}

I can think of some ways to do so in python (creating a list of range(1,n+1) and reverse it, using while and --i, …) but I wondered if there’s a more elegant way to do it. Is there?

EDIT:
Some suggested I use xrange() instead of range() since range returns a list while xrange returns an iterator. But in Python 3 (which I happen to use) range() returns an iterator and xrange doesn’t exist.

Now we will see solution for issue: How to loop backwards in python? [duplicate]


Answer

range() and xrange() take a third parameter that specifies a step. So you can do the following.

range(10, 0, -1)

Which gives

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 

But for iteration, you should really be using xrange instead. So,

xrange(10, 0, -1)

Note for Python 3 users: There are no separate range and xrange functions in Python 3, there is just range, which follows the design of Python 2’s xrange.

This question is answered By – Chinmay Kanchi

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0