Skip to content
Related Articles

Related Articles

Python List reverse()

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 07 Sep, 2022
Improve Article
Save Article

Python List reverse() is an inbuilt method in the Python programming language that reverses objects of the List in place i.e. it doesn’t use any extra space but it just modifies the original list.

Syntax: list_name.reverse()

Parameters: There are no parameters.

Returns: The reverse() method does not return any value but reverses the given object from the list.

Reverse a list using list reverse()

Here we are reversing the list using the list reverse() function in Python.

Python3




# Python3 program to demonstrate the
# use of reverse method
  
# a list of numbers
list1 = [1, 2, 3, 4, 1, 2, 6]
list1.reverse()
print(list1)
 
# a list of characters
list2 = ['a', 'b', 'c', 'd', 'a', 'a']
list2.reverse()
print(list2)

Output: 

[6, 2, 1, 4, 3, 2, 1]
['a', 'a', 'd', 'c', 'b', 'a']

Demonstrate the Error in reverse() Method

When anything other than list is used in place of list, then it returns an AttributeError.

Python3




# Python3 program to demonstrate the
# error in reverse() method
  
# error when string is used in place of list
string = "abgedge"
string.reverse()
print(string)

Output: 

Traceback (most recent call last):
  File "/home/b3cf360e62d8812babb5549c3a4d3d30.py", line 5, in 
    string.reverse() 
AttributeError: 'str' object has no attribute 'reverse' 

Practical Application

Given a list of numbers, check if the list is a palindrome

Python3




# Python3 program for the
# practical application of reverse()
 
list1 = [1, 2, 3, 2, 1]
 
# store a copy of list
list2 = list1.copy() 
 
# reverse the list
list2.reverse()
 
# compare reversed and original list
if list1 == list2:
    print("Palindrome")
else:
    print("Not Palindrome")

Output: 

Palindrome

Python3




list1 = list("naman")
 
# store a copy of list
list2 = list1.copy() 
 
# reverse the list
list2.reverse()
 
# compare reversed and original list
if list1 == list2:
    print("Palindrome")
else:
    print("Not Palindrome")

Output:

Palindrome

Note: Palindrome-sequence that reads the same backward as forwards.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!