22

I try to find common list of values for three different lists:

a = [1,2,3,4]
b = [2,3,4,5]
c = [3,4,5,6]

of course naturally I try to use the and operator however that way I just get the value of last list in expression:

>> a and b and c
out: [3,4,5,6]

Is any short way to find the common values list:

[3,4]

Br

PaulWebbster
  • 1,480
  • 2
  • 14
  • 27

3 Answers3

63

Use sets:

>>> a = [1, 2, 3, 4]
>>> b = [2, 3, 4, 5]
>>> c = [3, 4, 5, 6]
>>> set(a) & set(b) & set(c)
{3, 4}

Or as Jon suggested:

>>> set(a).intersection(b, c)
{3, 4}

Using sets has the benefit that you don’t need to repeatedly iterate the original lists. Each list is iterated once to create the sets, and then the sets are intersected.

The naive way to solve this using a filtered list comprehension as Geotob did will iterate lists b and c for each element of a, so for longer list, this will be a lot less efficient.

fhdrsdg
  • 10,297
  • 2
  • 41
  • 62
poke
  • 369,085
  • 72
  • 557
  • 602
12
out = [x for x in a if x in b and x in c]

is a quick and simple solution. This constructs a list out with entries from a, if those entries are in b and c.

For larger lists, you want to look at the answer provided by @poke

Geotob
  • 2,847
  • 1
  • 16
  • 26
4

For those still stumbling uppon this question, with numpy one can use:

np.intersect1d(array1, array2)

This works with lists as well as numpy arrays. It could be extended to more arrays with the help of functools.reduce, or it can simply be repeated for several arrays.

from functools import reduce
reduce(np.intersect1d, (array1, array2, array3))

or

new_array = np.intersect1d(array1, array2)
np.intersect1d(new_array, array3)
L. IJspeert
  • 371
  • 2
  • 5