0

I have a list of lists, like follow:

list = [[1,2,3],[2,3,4],[3,4,5],[3,5,6]]

I want to find the intersection of them in python 2.7, I mean

intersect_list = [3]

Thanks.

2
  • Have any code, yet? Commented Dec 9, 2016 at 19:55
  • @cricket_007 I tried pairwise intersection between a result and every element of list, but I think it is not an optimal way, should I write it here? Commented Dec 9, 2016 at 19:58

1 Answer 1

12

First, don't use list as a variable name - it hides the built in class.

Next, this will do it

>>> a = [[1,2,3],[2,3,4],[3,4,5],[3,5,6]]
>>> set.intersection(*map(set,a))
{3}

The map(set,a) simply converts it to a list of sets. Then you just unpack the list and find the intersection.

If you really need the result as a list, just wrap the call with list(...)

Sign up to request clarification or add additional context in comments.

7 Comments

You could use set(a[0]).intersection(*a[1:]) which would avoid needing to convert most of the lists to sets.
You could do set(m[0]).intersection(*m[1:]) for refusing of converting all the sublists to set.
Nifty use of the unpacking: python.org/dev/peps/pep-3132
Yeah, but I just prefer the straightforward call to map. Seems cleaner and more intuitive. You need to understand unpacking either way
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.