Python List reverse()
Last Updated :
09 May, 2023
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.
Python List reverse() Syntax
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.
List reverse() in Python Example
Reverse a list using list reverse()
Here we are reversing the list using the list reverse() function in Python.
Python3
list1 = [ 1 , 2 , 3 , 4 , 1 , 2 , 6 ]
list1.reverse()
print (list1)
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']
Error in reverse() Method
When anything other than list is used in place of list, then it returns an AttributeError.
Python3
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'
Reverse a List using the Slicing Operator
In this example, the [::-1] slicing operator creates a new list which is the reverse of the my_list.
Python3
my_list = [ 1 , 2 , 3 , 4 , 5 ]
reversed_list = my_list[:: - 1 ]
print (reversed_list)
|
Output :
[5, 4, 3, 2, 1]
Reversing a sublist using Slicing
In this example, we are reversing a sublist from index 1 to 3 using [::-1] operator.
Python3
my_list = [ 1 , 2 , 3 , 4 , 5 ]
print ( 'Original list:' , my_list)
my_list[ 1 : 4 ] = my_list[ 1 : 4 ][:: - 1 ]
print ( 'Reversed sublist:' , my_list)
|
Output :
Original list: [1, 2, 3, 4, 5]
Reversed sublist: [1, 4, 3, 2, 5]
Accessing Elements in Reversed Order
In this example, we are traversing the list in the reverse order.
Python3
my_list = [ 1 , 2 , 3 , 4 , 5 ]
for element in reversed (my_list):
print (element)
|
Output :
5
4
3
2
1
Reversing a list of mixed DataTypes
In this example, we are reversing the list of mixed data types with the reverse() function.
Python3
my_list = [ 1 , 'apple' , 2.5 , True ]
print ( 'Original list:' , my_list)
my_list.reverse()
print ( 'Reversed list:' , my_list)
|
Output :
Original list: [1, 'apple', 2.5, True]
Reversed list: [True, 2.5, 'apple', 1]
Practical Application
Given a list of numbers, check if the list is a palindrome.
Python3
list_arr = [ 1 , 2 , 3 , 2 , 1 ]
list_string = list ( "naman" )
list2 = list_arr.copy()
list3 = list_string.copy()
list2.reverse()
list3.reverse()
if list_arr = = list2:
print (list_arr, ": Palindrome" )
else :
print (list_arr, ": Not Palindrome" )
if list_string = = list3:
print (list_string, ": Palindrome" )
else :
print (list_string, ": Not Palindrome" )
|
Output
[1, 2, 3, 2, 1] : Palindrome
['n', 'a', 'm', 'a', 'n'] : Palindrome
Note: Palindrome-sequence that reads the same backward as forwards.
Please Login to comment...