In Python, there are many ways we can reverse a list. While we can use the list reverse() function, there are other ways to reverse a list in Python without the reverse() function.
The easiest way to reverse a list in Python without using reverse() is with slicing.
lst = [1,2,3,4]
lst = lst[::-1]
print(lst)
#Output:
[4,3,2,1]
You can also use recursion to reverse a list in Python.
lst = [1,2,3,4]
def reverse_list(l):
if len(l) == 1:
return l
return reverse_list(l[1:]) + l[0:1]
print(reverse_list(lst))
#Output:
[4,3,2,1]
You can also use a for loop to swap the items in the list, starting with swapping the first and last items, then the second and second to last items, and so on and so forth.
lst = [1, 2, 3, 4]
for i in range(int(len(lst)/2)):
item_at_i = lst[i]
lst[i] = lst[len(lst) - i - 1]
lst[len(lst) - i - 1] = item_at_i
print(lst)
#Output:
[4,3,2,1]
When using list variables in Python, we can easily perform list manipulation to change the values or order of the list variables.
One such manipulation is to reverse a list. In Python, there is a built-in function called reverse(), but there are other ways we can reverse a list without the reverse() function.
The easiest way to reverse a list in Python without using the reverse() function is with slicing.
Below is an example in Python of how to reverse a list without the use of the reverse() function.
lst = [1,2,3,4]
lst = lst[::-1]
print(lst)
#Output:
[4,3,2,1]
Reverse a List Without reverse() Function in Python Using Recursion
Another way we can reverse a list in Python without the reverse() function is with a recursive function.
For recursion, we need to define a base case and a recursive step.
The base case for our recursive reverse function is when our list has a length of one. The recursive step keeps slicing the list from the second element to the end and add the first element to the end.
Below is an example of how to use recursion to reverse a list in Python.
lst = [1,2,3,4]
def reverse_list(l):
if len(l) == 1:
return l
return reverse_list(l[1:]) + l[0:1]
print(reverse_list(lst))
#Output:
[4,3,2,1]
Reverse a List in Python Without reverse() Function Using For Loop
We can also use a for loop to reverse a list in Python.
To use a for loop for reversing a list without the reverse() function, we will swap items in the list in the following way. First, we swap the first and last items. Next, we continue with swapping the second and second to last items, then the third and third to last items, until we reach the middle of the list.
Below is an example of how to use a loop to reverse a list in Python.
lst = [1, 2, 3, 4]
for i in range(int(len(lst)/2)):
item_at_i = list[i]
lst[i] = lst[len(lst) - i - 1]
lst[len(lst) - i - 1] = item_at_i
print(lst)
#Output:
[4,3,2,1]
Hopefully this article has been useful for you to learn how to reverse a list without the reverse() function in Python.