Iterate backward Python | Example code

The list can Iterate backward in Python if read the last element first and then the last but one and so on till the element is at index 0.

To get Backward iteration in Python you can use the range function, List Comprehension, or reversed() function.

Example Backward iteration in Python

Python example codes.

Using range() Function

Starting with position -1 to read the list from the last index value also iterate through steps of -1.

list1 = ['Mon', 'Tue', 'Wed', 'Thu']

for i in range(len(list1) - 1, -1, -1):
    print(list1[i], end=' ')

Output: Using end keyword in print to get values in a single line.

Iterate backward Python

List Comprehension and [::-1]

This way slicing the list which starts from position -1 and goes back to the first position. And use for loop with an iterator used as the index of the element in the list.

list1 = ["A", "B", "C", "D"]

for i in list1[::-1]:
    print(i, end=" ")

Output: D C B A

Using reversed() function

The reversed() function is very straight forward it’s simply picking the list items and prints them in the reverse order.

list1 = [1, 2, 3, 4]
for i in reversed(list1):
    print(i)

Output:

4
3
2
1

How to loop backward in python?

You can do:

for item in my_list[::-1]:
    print item

The [::-1] slice reverses the list in the for loop (but won’t actually modify your list “permanently”).

How to count backward in for loop python?

# for i in range(start, end, step)
for i in range(5, 0, -1):
    print(i)

Output:

5
4
3
2
1

Do comment if you have any doubts and suggestions on this Python iteration topic.

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.