tags:

views:

573

answers:

4

I am trying to loop from 100 to 0. How do I do this in Python?

for i in range (100,0) doesn't work.

+12  A: 

Try range(100,-1,-1), the 3rd argument being the increment to use.

0x6adb015
you could also use xrange instead of range if you don't need the number list, but this is the correct answer.
cyborg_ar
Also I need to use this to delete items from the collection, so that's why just wanted the indices.
Joan Venge
+3  A: 
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]
kcwu
+4  A: 

In my opinion, this is the most readable:

for i in reversed(xrange(101)):
    print i,
Triptych
+2  A: 

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
Blixt