Python for loop Backward | Example code

Using reversed() or range(N, -1, -1) method to do for loop Backward iteration in Python.

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:

Python for loop Backward

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.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.