Python Program to Reverse a List

This article deals with some programs in Python that reverse a list given by user. Here are the list of programs covered in this article:

Find and Print Reverse of a List

The question is, write a Python program to find and print reverse of a list. The items of list must be provided by user at run-time. The answer to this question is the program given below:

mylist = list()
print("Enter 5 elements for the list: ")
for i in range(5):
    mylist.append(input())

print("\nOriginal list:", mylist)

revlist = mylist[::-1]
print("Reversed List:", revlist)

Here is its sample run. The snapshot given below shows the initial output produced by above Python program:

python program reverse a list

Now supply or provide the input say 1, 2, 3, 6, 4 as five elements and press ENTER key to find and print reverse of given list like shown in the snapshot given below:

reverse list python

Reverse a List of n Elements

Basically this is the modified version of previous program. As this program leaves the size of list to be defined by user at run-time. Rest of the things are similar to previous program.

mylist = list()
print("Enter the size of list: ", end="")
tot = int(input())
print("Enter", tot, "elements for the list: ", end="")
for i in range(tot):
    mylist.append(input())

print("\nOriginal list:", mylist)

revlist = mylist[::-1]
print("Reversed List:", revlist)

Here is its sample run with user input, 3 as size, 100, 102, 101 as three elements:

print reverse of a list python

Reverse a List using one by one Element initialization

This program uses another list to initialize elements of original list from its last index to zeroth index. In this way, the new list contains the original list items, but in reverse order like shown in the program given below:

mylist = list()

print("Enter the size of list: ", end="")
tot = int(input())
print("Enter", tot, "elements for the list: ", end="")
for i in range(tot):
    mylist.append(input())

print("\nOriginal list:", mylist)

revlist = list()
for i in range(tot-1, -1, -1):
    revlist.append(mylist[i])

print("Reversed List:", revlist)

Here is its sample run with user input, 4 as size and 200, 300, 400, 500 as four elements:

find reverse of a list python

Python Online Test


« Previous Program Next Program »


Liked this post? Share it!