How does tuple comparison work in Python?

PythonProgrammingServer Side Programming

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}

example

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

>>> a = (1, 2, 3, 4, 5)
>>> b = (9, 8, 7, 6, 5)
>>> set(a).instersection(set(b))
set([5])
raja
Published on 18-Apr-2018 10:51:52
Advertisements