Python | Compare tuples

Python Methods and Functions

Method # 1: Using all () + generator expression + zip ()
A combination of the above functions can be used to accomplish this task. In this we just compare all elements using all () . The cross-tuple is accessed with zip () and the generator expression gives us the logic to compare.

# Python3 demo code work
# Tuple comparison
# using generator expression + all () + zip ()

 
# initialize tuples

test_tup1 = ( 10 , 4 , 5 )

test_tup2 = ( 13 , 5 , 18 )

 
# print original tuples

print ( " The original tuple 1: " + str (test_tup1))

print ( "The original tuple 2:" + str (test_tup2))

 
# Tuple comparison
# using generator expression + all () + zip ()

res = all (x & lt; y for x, y in zip (test_tup1, test_tup2))

 
# print result

print ( "Are all elements in second tuple greater than first?:" + str (res))

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
A combination of the above functions can be used to accomplish this specific task. In this we perform logic expansion for each element using map () and generating the logic using a lambda function.

# Python3 demo code
# Tuple comparison
# using all () + lambda + map ()

 
# initialize tuples

test_tup1 = ( 10 , 4 , 5 )

test_tup2 = ( 13 , 5 , 18 )

 
# print original tuples

print ( " The original tuple 1: " + str (test_tup1))

print ( "The original tuple 2:" + str (test_tup2))

 
# Tuple comparison
# using all () + lambda + map ()

res = all ( map ( lambda i, j: i & lt; j, test_tup1, test_tup2))

 
# print result

print ( "Are all elements in second tuple greater than first?: " + str (res))

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 




Get Solution for free from DataCamp guru