Skip to content

Python compare tuples

  • by

Python compares tuples means comparing the first item of the first tuple is compared to the first item of the second tuple and if they are not equal no more comparison. And if equal then the second item is considered, then the third, and so on.

Python compare tuples

Simple example code.

tuple1 = (1, 2, 3)
tuple2 = (1, 2, 4)
tuple3 = (1, 2, 3)

print(tuple1 == tuple2)  # False
print(tuple1 == tuple3)  # True

print(tuple1 < tuple2)  # True

print(tuple1 > tuple2)  # False

Output:

Python compare tuples

Check if each element of one tuple is greater/smaller than the corresponding index in another.

tuple1 = (1, 2, 3)
tuple2 = (1, 2, 4)

# Comparing tuples
res = all(x < y for x, y in zip(tuple1, tuple2))

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

Output: Are all elements in second tuple greater than first? : False

Compare unequal tuples

tuple1 = (1,2,3)
tuple2 = (4,5,6,7)
 
print( tuple1 < tuple2 )   # True

Do comment if you have any doubts or suggestions on this Python compare topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *