;

Python Program to Reverse a Given List


Tutorialsrack 03/05/2020 Python

In this Python Program, we will learn how to reverse a given list. In this program, we reverse the list with or without using the python built-in reverse() function.

Here is the source code of the program to reverse a given list 

Program 1: Python Program to Reverse a List Using reverse() Function

In this program, we used the python built-in function reverse(). The reverse() is used to reverse the element in the list and it does not return any value.

Python Program to Reverse a List Using reverse() Function
# Python Program to Reverse a List Using reverse() Function

NumList = []

# Take the Input From the User
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)

NumList.reverse()
print("\nThe Result of a Reverse List = ", NumList)
Output

Enter the Total Number of List Elements: 6

Enter the Value of 1 Element: 45

Enter the Value of 2 Element: 123

Enter the Value of 3 Element: 456

Enter the Value of 4 Element: 852

Enter the Value of 5 Element: 695

Enter the Value of 6 Element: 456

 

Original List:  [45, 123, 456, 852, 695, 456]

 

The Result of a Reverse List =  [456, 695, 852, 456, 123, 45]

Program 2: Python Program to Reverse a List Without Using the reverse() function

Python Program to Reverse a List Without Using the reverse() function
# Python Program to Reverse a List Without Using reverse() function

NumList = []

# Take the Input From the User
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)    

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)
Output

Enter the Total Number of List Elements: 5

Enter the Value of 1 Element: 456

Enter the Value of 2 Element: 256

Enter the Value of 3 Element: 321

Enter the Value of 4 Element: 485

Enter the Value of 5 Element: 698

 

Original List:  [456, 256, 321, 485, 698]

 

The Result of a Reverse List =  [698, 485, 321, 256, 456]


Related Posts



Comments

Recent Posts
Tags