In this Python program, we will learn how to reverse a list using recursion. In this program, we create a recursive function to reverse a list.
Here is the source code of the program to reverse a list using recursion.
# Python Program to Reverse a List using Recursion
# Define a Function
def reverse_list(NumList, i, j):
if(i < j):
temp = NumList[i]
NumList[i] = NumList[j]
NumList[j] = temp
reverse_list(NumList, i + 1, j-1)
NumList = []
Number = int(input("Enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
value = int(input("Enter the Value of %d Element: " %i))
NumList.append(value)
# Print the List Entered By the User
print("\nOriginal List: ",NumList)
reverse_list(NumList, 0, Number - 1)
print("\nThe Result of a Reverse List = ", NumList)
Enter the Total Number of List Elements: 7
Enter the Value of 1 Element: 46
Enter the Value of 2 Element: 25
Enter the Value of 3 Element: 63
Enter the Value of 4 Element: 45
Enter the Value of 5 Element: 89
Enter the Value of 6 Element: 74
Enter the Value of 7 Element: 65
Original List: [46, 25, 63, 45, 89, 74, 65]
The Result of a Reverse List = [65, 74, 89, 45, 63, 25, 46]
Comments