Python | Reverse a list using recursion

def rev_my_list(my_list, l, r):
    if l >= r:
        return my_list

    temp = my_list[l]
    my_list[l] = my_list[r]
    my_list[r] = temp

    return rev_my_list(my_list,l+1,r-1)

lst = []
n = int(input("Enter number of elements : "))
  
for i in range(0, n):
    ele = int(input())
    lst.append(ele) 
      
L = 0
R = len(lst)-1
print('List entered by the user is:',lst)
print('Reverse of the entered list :',rev_my_list(lst,L,R))
Enter number of elements : 7
10
11
12
13
14
15
16
List entered by the user is: [10, 11, 12, 13, 14, 15, 16]
Reverse of the entered list : [16, 15, 14, 13, 12, 11, 10]

Explanation:

Here in this approach, we first took the input from the user about the number of elements in the list, and based on that we used a for loop till that range to accept the input and add the elements to the list. We passed three parameters to the function named rev_my_list. The list of elements, l, and r, where l’s value is 0 and r’s value is the length of the list – 1. Now inside the function, we used a conditional statement to check that if the value of l is greater than r then we return the list, and if not then we use the concept of swap.

Here in swapping, we used the temp variable that holds our list. Now at the 0th index of the my_list, we store the last element of the my_list and simply store the value in the temp variable at the index value equivalent to r in my_list. This goes on until the value of l is greater than r. Once that is achieved, we can confirm that our list is reversed.

Here is the end of our article. We solved the given problem using recursion using the swapping concept.

Share:

Author: Ayush Purawr