List of pythons | reverse()

Python Methods and Functions

Syntax :

 list_name.reverse () 

Parameters :

 There are no parameters 

Returns :

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

Code # 1:

# Python3 demo program
# using the reverse method

 
# list of numbers

list1 = [ 1 , 2 , 3 , 4 , 1 , 2 , 6

list1.reverse () 

print (list1) 

 
# list of characters

list2 = [ 'a' , ' b' , 'c' , ' d' , 'a' , 'a'

list2.reverse () 

print (list2) 

 

Exit:

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

Error :

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

Code # 2:

# Python3 demo
# error in reverse () method

 
# error when string is used instead of list

string = "abgedge"  
string.reverse () 

print (string)

Exit :

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

Practical use:
Given list of numbers, check if the list is palindrome. 
Note: palindrome sequence that reads the same as forward

Code # 3:

# Python3 program for
# practical use of reverse ()

 

list1 = [ 1 , 2 , 3 , 2 , 1 ]

  
# save a copy of the list

list2 = list1.copy () 

  
# reverse the list
list2.reverse () 

 
# compare reversed and original list

if list1 = = list2:

print ( " Palindrome "

else :

print ( "Not Palindrome "

Exit :

 Palindrome 



Tutorials