To reverse for loop in Python just need to read the last element first and then the last but one and so on till the element is at index 0. You can do it with the range function, List Comprehension, or reversed() function.
Example Reverse for loop in Python
Simple example code:
Using reversed() function
A code demonstrates how to backward iteration is done with reversed() function on the for-loop.
list1 = [1, 2, 3, 4]
for i in reversed(list1):
print(i)
Output:
Using range() Function
range() and xrange() take a third parameter that specifies a step. So you can do the following.
list1 = ['Mon', 'Tue', 'Wed', 'Thu']
for i in range(len(list1) - 1, -1, -1):
print(list1[i], end=' ')
Output: Thu Wed Tue Mon
Python’s foreach backward Example
Use built-in reversed() function.
for i in reversed(range(5)):
print(i)
Output:
4
3
2
1
0
Note: Python 3 has not separate range
and xrange
functions, there is just range
, which follows the design of Python 2’s xrange
.
Do comment if you have any doubts and suggestions on this Python loop topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.