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:
OR
Use that range() function in for loop and use the 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 or suggestions on this Python reverse topic.
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.