Loop backwards using indices in Python?

PythonLoops

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

In my opinion, this is the most readable:

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

Solution 3 - Python

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

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

Solution 5 - Python

Why your code didn't work

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)

Solution 6 - Python

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.

Solution 7 - Python

The simple answer to solve your problem could be like this:

for i in range(100):
    k = 100 - i
    print(k)

Solution 8 - Python

You might want to use the reversed function in python. Before we jump in to the code we must remember that the range function always returns a list (or a tuple I don't know) so range(5) will return [0, 1, 2, 3, 4]. The reversed function reverses a list or a tuple so reversed(range(5)) will be [4, 3, 2, 1, 0] so your solution might be:

for i in reversed(range(100)):
    print(i)

Solution 9 - Python

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

Solution 10 - Python

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

Solution 11 - Python

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    

Solution 12 - Python

I wanted to loop through a two lists backwards at the same time so I needed the negative index. This is my solution:

a= [1,3,4,5,2]
for i in range(-1, -len(a), -1):
    print(i, a[i])

Result:

-1 2
-2 5
-3 4
-4 3
-5 1

Solution 13 - Python

You can also create a custom reverse mechanism in python. Which can be use anywhere for looping an iterable backwards

class Reverse:
    """Iterator for looping over a sequence backwards"""
    def __init__(self, seq):
        self.seq = seq
        self.index = len(seq)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index -= 1
        return self.seq[self.index]


>>> d = [1,2,3,4,5]
>>> for i in Reverse(d):
...   print(i)
... 
5
4
3
2
1

Solution 14 - Python

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')

Solution 15 - Python

Oh okay read the question wrong, I guess it's about going backward in an array? if so, I have this:

array = ["ty", "rogers", "smith", "davis", "tony", "jack", "john", "jill", "harry", "tom", "jane", "hilary", "jackson", "andrew", "george", "rachel"]


counter = 0   

for loop in range(len(array)):
    if loop <= len(array):
        counter = -1
        reverseEngineering = loop + counter
        print(array[reverseEngineering])

Solution 16 - Python

It works well with me

for i in range(5)[::-1]:
    print(i,end=' ')

output : 4 3 2 1 0

Solution 17 - Python

a = 10
for i in sorted(range(a), reverse=True):
    print i

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoan VengeView Question on Stackoverflow
Solution 1 - Python0x6adb015View Answer on Stackoverflow
Solution 2 - PythonKenan BanksView Answer on Stackoverflow
Solution 3 - PythonkcwuView Answer on Stackoverflow
Solution 4 - PythonBlixtView Answer on Stackoverflow
Solution 5 - PythonmythicalcoderView Answer on Stackoverflow
Solution 6 - PythonAndy T.View Answer on Stackoverflow
Solution 7 - PythonenotedView Answer on Stackoverflow
Solution 8 - PythonAdhritView Answer on Stackoverflow
Solution 9 - PythonpnoobView Answer on Stackoverflow
Solution 10 - Pythonuser2220115View Answer on Stackoverflow
Solution 11 - PythonMikeView Answer on Stackoverflow
Solution 12 - PythonEmanuel LindströmView Answer on Stackoverflow
Solution 13 - Pythonmohammed wazeemView Answer on Stackoverflow
Solution 14 - PythonTabula RasaView Answer on Stackoverflow
Solution 15 - PythondarrellView Answer on Stackoverflow
Solution 16 - PythonAdnan AlarefView Answer on Stackoverflow
Solution 17 - PythonboombaView Answer on Stackoverflow