-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?

1
  • 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. Commented Feb 14, 2018 at 17:00

3 Answers 3

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']
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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'}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.