Loop backwards using indices in Python?
Solution 1:
Try range(100,-1,-1)
, the 3rd argument being the increment to use (documented here).
("range" options, start, stop, step are documented here)
Solution 2:
In my opinion, this is the most readable:
for i in reversed(xrange(101)):
print i,
Solution 3:
for i in range(100, -1, -1)
and some slightly longer (and slower) solution:
for i in reversed(range(101))
for i in range(101)[::-1]
Solution 4:
Generally in Python, you can use negative indices to start from the back:
numbers = [10, 20, 30, 40, 50]
for i in xrange(len(numbers)):
print numbers[-i - 1]
Result:
50
40
30
20
10