Python reverse() Function

The reverse() function in Python is used to reverse the elements of a list. For example:

x = [12, 34, 45, 6]
x.reverse()
print(x)

The output produced by above Python program, is given below:

[6, 45, 34, 12]

Python reverse() Function Syntax

The syntax of reverse() function in Python is:

listName.reverse()

Python reverse() Function Example

The program given below is a simple example of reverse() function that is used to reverse a list, entered by user:

print("How many element to store in the list ? ", end="")
tot = int(input())
print("Enter", tot, "elements: ", end="")
mylist = []
for i in range(tot):
    element = input()
    mylist.append(element)

print("\nThe list is:")
for i in range(tot):
    print(mylist[i], end=" ")

print("\n\nReversing the list...")
mylist.reverse()

print("\nNow the list is:")
for i in range(tot):
    print(mylist[i], end=" ")
print()

The snapshot given below shows the sample run with user input 4 as list size, 98, 87, 76, 65 as four elements:

python reverse function

Python Online Test


« Previous Function Next Function »