How to reverse a list in Python using for loop | Example code

Using the while loop or for loop and range() function is the way to reverse a list in Python using a loop.

Example reverse a list in Python using for loop

Simple example code of different ways to Iterate over a List in Reverse Order using for loop.

Example 1: Python reverse list using for loop and range()

Traverse [n-1, -1) , in the opposite direction.

def reverse(lst):
    # Traverse [n-1, -1) , in the opposite direction.
    for i in range(len(lst) - 1, -1, -1):
        yield lst[i]


list1 = [1, 2, 3, 4, 5, 6, 7]
res = list(reverse(list1))

print(res)

Output:

How to reverse a list in Python using for loop

OR

Use that range() function in for loop and use random access operator [] to access elements in reverse i.e.

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

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

Output: CBA

Iterate over the list using for loop and reversed()

list1 = [1, 2, 3, 4, 5, 6, 7]

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

Do comment if you have any doubts and suggestions on this Python reverse 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.