Write a Python Program to reverse List Items with a practical example.
Python Program to Reverse List Items
This python program allows user to enter the length of a List. Next, we used Python For Loop to add numbers to the list.
# Python Program to Reverse List Elements NumList = [] Number = int(input("Please enter the Total Number of List Elements: ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) NumList.reverse() print("\nThe Result of a Reverse List = ", NumList)
TIP: Python reverse function is used to reverse the elements in a List.
Program to Reverse List Items without using reverse
In this python program, we are using a While loop. Inside the while loop, we performed the Swapping with the help of the third variable. I suggest you refer Swap two Numbers article to understand the Python logic.
# Python Program to Reverse List Elements NumList = [] Number = int(input("Please enter the Total Number of List Elements: ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) j = Number - 1 i = 0 while(i < j): temp = NumList[i] NumList[i] = NumList[j] NumList[j] = temp i = i + 1 j = j - 1 print("\nThe Result of a Reverse List = ", NumList)
Program to Reverse List Items using Functions
This program to reverse List items is the same as the above. However, we separated the logic using Functions
# Python Program to Reverse List Elements def reverse_list(NumList, num): j = Number - 1 i = 0 while(i < j): temp = NumList[i] NumList[i] = NumList[j] NumList[j] = temp i = i + 1 j = j - 1 NumList = [] Number = int(input("Please enter the Total Number of List Elements: ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) reverse_list(NumList, Number) print("\nThe Result of a Reverse List = ", NumList)
Program to Reverse Items in a List using Recursion
This program reverses the List items by calling functions recursively
# Python Program to Reverse List Elements 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("Please enter the Total Number of List Elements: ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) reverse_list(NumList, 0, Number - 1) print("\nThe Result of a Reverse List = ", NumList)