views:

311

answers:

2

Hi,

I have a list of lists (sublist) that contains numbers and I only want to keep those exists in all (sub)lists.

Example:

x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]]

output => [3, 4]

How can I do this?

+7  A: 
common = set(x[0])
for l in x[1:]:
    common &= set(l)
print list(common)

or:

import operator
print reduce(operator.iand, map(set, x))
Ned Batchelder
I originally started with set(), it's fixed now.
Ned Batchelder
Yep, I posted an answer which modified yours and worked, but by the time I'd got back you edited it. Sadly, stackoverflow won't let me +1 you, since I upvoted, and then undid my upvote. Great answer though!
Dominic Rodger
+4  A: 

In one liner:

>>> reduce(set.intersection, x[1:], set(x[0]))
set([3, 4])
Nadia Alramli
or list(reduce(set.intersection, x[1:], set(x[0])))
grokus