-1

I want to intersect several(e.g. 3) lists.

a = ["a", "b", "c"]
b = ["d", "e", "f"]
c = ["g", "h", "i"]

There is an intersect1d method from numpy, but it accepts only 2 arrays per call, so, that is not that comfortable to use. Are their any methods, which accepts a bunch of lists at once?

Ladenkov Vladislav
  • 1,247
  • 2
  • 21
  • 45
  • Just convert to `set` and use the `&` operator- for example: `list(set(a)&set(b)&set(c))`. However, the intersection for your example is an empty set. – pault Feb 14 '18 at 17:00

3 Answers3

1

Intersect works with Sets and uses & to perform the operation. As it sits, you will return an empty set. If you change your lists a little, you can see it work.

a = ["a", "b", "c"]
b = ["d", "a", "f"]
c = ["g", "h", "a"]

set(a) & set(b) & set(c)
dfundako
  • 8,022
  • 3
  • 18
  • 34
1

If you had your lists in a list, you could do the following:

a = ["a", "b", "c"]
b = ["a", "e", "f"]
c = ["a", "h", "i"]

lists = [a, b, c]
intersection = list(reduce(lambda u, v: u&v, (set(x) for x in lists)))
print(intersection)
#['a']
pault
  • 41,343
  • 15
  • 107
  • 149
1

This is my preferred syntax:

a = ["a", "b", "c"]
b = ["a", "e", "f"]
c = ["a", "h", "i"]

set.intersection(*map(set, (a, b, c)))

# {'a'}
jpp
  • 159,742
  • 34
  • 281
  • 339