+1 vote
in Programming Languages by (7.9k points)
edited by
How to find the common elements in two or more lists in Python?

1 Answer

0 votes
by (15.3k points)

There are several ways to find the common elements in two or more python lists. When you have only two lists, you can use one of the following approaches:

>>> a=[1, 2, 4, 3]
>>> b=[3,4,5,6]
>>> set(a).intersection(b)
{3, 4}
>>> [i for i in b if i in a]
[3, 4]
>>> import numpy as np
>>> np.intersect1d(a,b)
array([3, 4])

When you have more than two lists, you can use one of the following approaches:

>>> a=[1, 2, 4, 3]
>>> b=[3,4,5,6]
>>> c=[3,7,8,9,10]
>>> [i for i in c if i in a and i in b]
[3]
>>> set(a).intersection(c,b)
{3}
>>> from functools import reduce
>>> reduce(np.intersect1d,(a,b,c))
array([3])

...