Skip to content
Related Articles

Related Articles

Python – How to Check if two lists are reverse equal

View Discussion
Improve Article
Save Article
  • Last Updated : 07 Sep, 2022
View Discussion
Improve Article
Save Article

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. 

Python3




# 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))

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. 

Python3




# 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))

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 3: Using insert function

Python3




# Python code to check if twi
# lists are reverse equal or not
 
lst1 = [5, 6, 7, 8]; lst2 = [8, 7, 6, 5]
l = []
# reversing list 2 elements
# using insert function
for i in lst2:
    l.insert(0, i)
# comparing the first list with
# reverse list if both are equal
# then return true otherwise false
if lst1 == l:
    print("True")
else:
    print("False")
 
    # this code is contributed by gangarajula laxmi

Output

True

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!