Implementing Reverse Loop in Python

Quick Answer


for i in range(3,0,-1):
	print('Reverse Python Loop-%d' %(i))

Output

Reverse Python Loop-3
Reverse Python Loop-2
Reverse Python Loop-1

Detail Explanation

In C/C++ programming we can do something like:

for(i=5;i>0;i--)
{
    printf("%d\t", i);	
}

to loop backward (reverse) to produce output like:

5    4    3    2    1

In python same thing can be achieved by using range() function with third arguments. To understand this, first we need to understand range() function in detail. Let's look at this first:

First, let's run:


for i in range(5):
	print(i)

Which gives:

0
1
2
3
4

In above program range(5) generates number 0, 1, 2, 3, 4 and we iterate through them to print. In general when one argument say (n) is given to range function then it generates number from 0 to n-1 and each time updating value by 1.

Second, let's run:


for i in range(2,5):
	print(i)

Which gives:

2
3
4

In above program range(2,5) generates number 2, 3, 4 and we iterate through them to print. In general when two arguments say (n1, n2) are given to range function then it generates number from n1 to n2-1 and each time updating value by 1.

Third, let's run:


for i in range(1,8,2):
	print(i)

Which gives:

1
3
5
7

In above program range(1,8,2) generates number 1, 3, 5, 7 and we iterate through them to print. In general when three arguments say (n1, n2, n3) are given to range function then it generates number from n1 to n2-1 with update value of n3.

So, to implement reverse loop we can use negative value in update argument of range function.

Python Reverse Loop Example


for i in range(8,0,-1):
	print('Reverse Python Loop-%d' %(i))

Output of above program is:

Reverse Python Loop-8
Reverse Python Loop-7
Reverse Python Loop-6
Reverse Python Loop-5
Reverse Python Loop-4
Reverse Python Loop-3
Reverse Python Loop-2
Reverse Python Loop-1