How to loop backwards in python? [duplicate]
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
andxrange
functions in Python 3, there is justrange
, which follows the design of Python 2'sxrange
.