Python | Compare tuples

Sometimes, while working with records, we can have a problem in which we need to check if each element of one tuple is greater/smaller than it’s corresponding index in other tuple. This can have many possible applications. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using all() + generator expression + zip()
The combination of above functionalities can be used to perform this task. In this, we just compare all elements using all(). The cross tuple access is done by zip() and generator expression gives us the logic to compare.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Comparing tuples
# using generator expression + all() + zip()
  
# initialize tuples 
test_tup1 = (10, 4, 5)
test_tup2 = (13, 5, 18)
  
# printing original tuples 
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
  
# Comparing tuples
# using generator expression + all() + zip()
res = all(x < y for x, y in zip(test_tup1, test_tup2))
  
# printing result
print("Are all elements in second tuple greater than first ? : " + str(res))

chevron_right


Output :



The original tuple 1 : (10, 4, 5)
The original tuple 2 : (13, 5, 18)
Are all elements in second tuple greater than first ? : True

 

Method #2 : Using all() + map() + lambda
The combination of above functionalities can be used to perform this particular task. In this, we perform extension of logic to each element using map() and logic generation by lambda function.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Comparing tuples
# using all() + lambda + map()
  
# initialize tuples 
test_tup1 = (10, 4, 5)
test_tup2 = (13, 5, 18)
  
# printing original tuples 
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
  
# Comparing tuples
# using all() + lambda + map()
res = all(map(lambda i, j: i < j, test_tup1, test_tup2))
  
# printing result
print("Are all elements in second tuple greater than first ? : " + str(res))

chevron_right


Output :

The original tuple 1 : (10, 4, 5)
The original tuple 2 : (13, 5, 18)
Are all elements in second tuple greater than first ? : 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.