Python – How to Check if two lists are reverse equal

Sometimes, while working with Python lists, we can have a problem in which we need to check if two lists are reverse of each other. This kind of problem can have application in many domains such as day-day programming and school programming. Let’s discuss certain ways in which this task can be performed.

Input : test_list1 = [5, 6, 7], test_list2 = [7, 6, 5]
Output : True

Input : test_list1 = [5, 6], test_list2 = [7, 6]
Output : False

Method #1 : Using reversed() and "==" operator
The combination of above functions can be used to solve this problem. In this, we perform the task of reversing using reversed() and testing for equality using “==” operator.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Check if two lists are reverse equal
# Using reversed() + == operator
  
# initializing lists
test_list1 = [5, 6, 7, 8]
test_list2 = [8, 7, 6, 5]
  
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# Check if two lists are reverse equal
# Using reversed() + == operator
res = test_list1 == list(reversed(test_list2))
  
# printing result 
print("Are both list reverse of each other ? : " + str(res))

chevron_right


Output :



The original list 1 : [5, 6, 7, 8]
The original list 2 : [8, 7, 6, 5]
Are both list reverse of each other ? : True

 

Method #2 : Using list slicing + “==” operator
This is yet another way to solve this problem. In this, we perform the task of list reversing using slice technique.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Check if two lists are reverse equal
# Using list slicing + "==" operator
  
# initializing lists
test_list1 = [5, 6, 7, 8]
test_list2 = [8, 7, 6, 5]
  
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# Check if two lists are reverse equal
# Using list slicing + "==" operator
res = test_list1 == test_list2[::-1]
  
# printing result 
print("Are both list reverse of each other ? : " + str(res))

chevron_right


Output :

The original list 1 : [5, 6, 7, 8]
The original list 2 : [8, 7, 6, 5]
Are both list reverse of each other ? : True



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.