Python Program to Reverse List

Write a Python Program to reverse List Items or reverse a list elements with a practical example.

Python Program to Reverse List Items

It allows the user to enter the length of a List. Next, we used Python For Loop to add numbers to the list.

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)
Python Program to Reverse List Elements 1

TIP: Python function is used to invert the elements in a List.

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.

NumList = []

Number = int(input("Please enter the Total Numbers : "))
for i in range(1, Number + 1):
    value = int(input("%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 =  ", NumList)
Please enter the Total Numbers : 3
1 Element : 1
2 Element : 2
3 Element : 3

The Result =   [3, 2, 1]

Program to Reverse a List in Python using Functions

This List items program is the same as the above. However, we separated the logic using Functions

def reverseList(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 Elements: "))
for i in range(1, Number + 1):
    value = int(input("%d Element : " %i))
    NumList.append(value)
    
reverseList(NumList, Number)
print("\nThe Result =  ", NumList)
Please enter the Total Number of Elements: 5
1 Element : 10
2 Element : 20
3 Element : 30
4 Element : 40
5 Element : 50

The Result =   [50, 40, 30, 20, 10]

This program reverses the List items by calling functions recursively

def reverseList(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 Elements: "))
for i in range(1, Number + 1):
    value = int(input("%d Element : " %i))
    NumList.append(value)
    
reverseList(NumList, 0, Number - 1)
print("\nThe Result =  ", NumList)
Please enter the Total Number of Elements: 6
1 Element : 12
2 Element : 13
3 Element : 14
4 Element : 15
5 Element : 16
6 Element : 27

The Result =   [27, 16, 15, 14, 13, 12]