Table of Contents

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 addition to 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 a tuple on the left-hand side is compared with the first element of a tuple on the right-hand side, the second element of a tuple on the left-hand side is compared with the second element of a 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.

Share this post:

Leave a comment

Similar Posts


One Day or Day One, you decide.