views:

212

answers:

3

what's the easiest way to take the intersection of N-many lists in python?

if I have two lists a and b, I know I can do:

a = set(a)
b = set(b)
intersect = a.intersection(b)

but I want to do something like a & b & c & d & ... for an arbitrary set of lists (ideally without converting to a set first, but if that's the easiest / most efficient way, I can deal with that.)

I.e. I want to write a function intersect(*args) that will do it for arbitrarily many sets efficiently. What's the easiest way to do that?

EDIT: My own solution is reduce(set.intersection, [a,b,c]) -- is that good?

thanks.

+1  A: 

This works with 1 or more lists and does not use multiple parameters:

>>> def intersection(*listas):
...     return set(listas[0]).intersection(*listas[1:]) 
...     
>>> intersection([1,2,3,4],[4,5,6],[2,4,5],[1,4,8])
set([4])
>>> intersection([1,2,3,4])
set([1, 2, 3, 4])
>>> 

Not sure this is better than other answers, anyway.

joaquin
+1  A: 
lists = [[5,4,3], [4,2], [6,2,3,4]]

try:
    # the following line makes one intersection too much, but I don't think
    # this hurts performance noticably.
    intersected = set(lists[0]).intersection(*lists)
except ValueError:
    # no lists[0]
    intersected = set()

print intersected         # set([4])

Sets can be intersected with any iterable, there's no need to convert it into a set first.

Georg
+9  A: 

This works for 1 or more lists. The 0 lists case is not so easy, because it would have to return a set that contains all possible values.

def intersection(first, *others):
    return set(first).intersection(*others)
Paul Hankin
Beautiful. Really simple.
Georg
And thus the beauty of using built-ins.
jathanism