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)
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)
Note: Python 3 has not separate
xrange functions, there is just
range, which follows the design of Python 2’s
Do comment if you have any doubts and suggestions on this Python loop topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.