Using reversed() or range(N, -1, -1) method to do for loop Backward iteration in Python.
For example for loop backward in Python
Simple example code looping backward and having shorthands to do it.
Using reversed() function
Use the reversed function for the for loop and the iteration will start occurring from the last than the conventional counting.
lst = [1, 2, 3, 4, 5]
for num in reversed(lst):
print(num, end=" ")
Output:
Loop backward using indices in Python?
Generally in Python, you can use negative indices to start from the back:
for i in range(10, -1, -1):
print(i, end=" ")
Output: 10 9 8 7 6 5 4 3 2 1 0
Best way to loop over a python string backward
Use reversed built-in function to loop over a Python string backward.
for c in reversed(string):
print c
The reversed() call will make an iterator rather than copying the entire string.
st1 = "Hello"
for c in reversed(st1):
print(c, end=" ")
Output: o l l e H
Do comment if you have any doubts and suggestions on this Python for loop tutorial.
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.