Tuple Comparison in Python

Posted on Wed 12 June 2019 in Python

Comparing tuples in Python

Comparing strings in Python is intuitive. But did you know that comparing tuples in Python also works the same way? Consider the following examples:

>>> (100, 200, 300) == (100, 200, 300)
True
>>> (100, 200, 300) == (100, 200, 400)
False

In additon to the the equality operator(==), we can use any comparison operator (<, >, <=, >=) to compare tuples as shown in the examples below:

>>> (100, 200, 300) < (100, 200, 250)  # 300 greater than 250
False
>>> (100, 200, 300) > (50, 200, 300)   # 100 greater than 50
True
>>> (100, 200, 300) <= (100, 200, 300) # element wise comparison proves equal
True
>>> (100, 200, 300) >= (100, 150, 300) # 200 greater than 150
True

In the above examples, it is clear that tuple comparison in Python happens element-wise, the first element of tuple on the left hand side is compared with first element of tuple on the right hand side, the second element of tuple on the left hand side is compared with second element of tuple on the right hand side and so on.

Conclusion

We can do tuple comparison in Python just like we do string comparison. Using tuple comparison makes the code more readable too.