How do we compare two tuples in Python?


Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on. 

example

>>> a = (1, 2, 3)
>>> b = (1, 2, 5)
>>> a < b
True

There is another type of comparison that takes into account similar and different elements. This can be performed using sets. Sets will take the tuples and take only unique values. Then you can perform a & operation that acts like intersection to get the common objects from the tuples. 

example

>>> a = (1, 2, 3, 4, 5)
>>> b = (9, 8, 7, 6, 5)
>>> set(a) & set(b)
{5}

You can also use set.intersection function to perform this operation. 

example

>>> a = (1, 2, 3, 4, 5)
>>> b = (9, 8, 7, 6, 5)
>>> set(a).instersection(set(b))
set([5])

Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician

Updated on: 05-Mar-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements