How to reverse a list in python without using reverse function
Introduction
In this Python code snippet post, we are going to implement a list reverse function from the scratch without using any builtin functions.
Let us see how…
Iterative solution
We can use a for loop to swap the first and last items, the second and the one before the last item and so on until the list is reversed in place. The number of iterations needed is half the list size. If the list has an odd number of items then the middle item will stay in its place.
Here is an example Python code to do that
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Example input list of numbers numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Get list length L = len(numbers) # i goes from 0 to the middle for i in range(int(L/2)): # Swap each number with the number in # the mirror position for example first # and last n = numbers[i] numbers[i] = numbers[L-i-1] numbers[L-i-1] = n # At this point the list should be reversed print(numbers) |
Recursion solution
We can write a recursive reverse function to reverse a list. The stopping condition occurs when the list is one item in length in such case we just return that list otherwise we return list concatenation constructed from the first item and the recursive reverse of the rest of the items. For example Reverse([1, 2, 3, 4]) = Reverse([2, 3, 4]) + [1].
Here is an example implementation…
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Example input list of numbers numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Function takes a list as input def Reverse(numbers): # Base case when the list is only one item if (len(numbers)==1): return numbers # Otherwise return Reverse(numbers[1:]) + numbers[0:1] # Test function print(Reverse(numbers)) |
I hope this post was useful. Thanks for visiting
this method will only work for list that has even number of elements
NO it works for both odd and even.
it works for both the recursive method has nothing to do with even