Home » Python » Loop backwards using indices in Python?

# Loop backwards using indices in Python?

Questions:

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.

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

Questions:

In my opinion, this is the most readable:

``````for i in reversed(xrange(101)):
print i,
``````

Questions:
``````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]
``````

Questions:

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
``````

Questions:

Another solution:

``````z = 10
for x in range (z):
y = z-x
print y
``````

Result:

``````10
9
8
7
6
5
4
3
2
1
``````

Tip:
If you are using this method to count back indices in a list, you will want to -1 from the ‘y’ value, as your list indices will begin at 0.

Questions:

Short and sweet. This was my solution when doing codeAcademy course. Prints a string in rev order.

``````def reverse(text):
string = ""
for i in range(len(text)-1,-1,-1):
string += text[i]
return string
``````

Questions:

`for var in range(10,-1,-1)` works

Questions:

You code `for i in range (100, 0)` is fine, except

the third parameter (`step`) is by default `+1`. So you have to specify 3rd parameter to range() as `-1` to step backwards.

``````for i in range(100, -1, -1):
print(i)
``````

NOTE: This includes 100 & 0 in the output.

There are multiple ways.

Better Way

For pythonic way, check PEP 0322.

This is Python3 pythonic example to print from 100 to 0 (including 100 & 0).

``````for i in reversed(range(101)):
print(i)
``````

Questions:

You can always do increasing range and subtract from a variable in your case `100 - i` where `i in range( 0, 101 )`.

``````for i in range( 0, 101 ):
print 100 - i
``````

Questions:

I tried this in one of the codeacademy exercises (reversing chars in a string without using reversed nor :: -1)

``````def reverse(text):
chars= []
l = len(text)
last = l-1
for i in range (l):
chars.append(text[last])
last-=1

result= ""
for c in chars:
result += c
return result
print reverse('hola')
``````

Questions:
``````a = 10