How do we compare two lists in Python?

PythonProgramming

The easiest way to do this is use sets. Sets will take the lists and take only unique values. Then you can perform a & operation that acts like intersection to get the common objects from the lists. 

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])
raja
Published on 18-Apr-2018 13:52:17
Advertisements