How to Reverse a List in Python Without Using the Reverse Function?

Estimated read time 1 min read

There are multiple ways to reverse a list in Python without using the built-in reverse() function. Here are a few:

  1. Using Slicing: You can use slicing to create a copy of the list in reverse order:
my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print(reversed_list)
  1. Using a Loop: You can create a new list and add each element from the original list in reverse order using a loop:
my_list = [1, 2, 3, 4, 5]
reversed_list = []
for i in range(len(my_list) - 1, -1, -1):
    reversed_list.append(my_list[i])
print(reversed_list)
  1. Using the reversed() Function: You can use the reversed() function to iterate over the list in reverse order and create a new list:
my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list)
  1. Using the pop() Method: You can remove elements from the end of the list and add them to a new list until the original list is empty:
my_list = [1, 2, 3, 4, 5]
reversed_list = []
while my_list:
    reversed_list.append(my_list.pop())
print(reversed_list)

All these methods will produce the same output:

[5, 4, 3, 2, 1]

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply