8

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.

3
  • On reduce(), it's not exactly the best idea, since it's being phased out in Python 3. It's also slower, from what I've heard, compared to a for loop. Commented Jun 1, 2010 at 21:12
  • Duplicate: stackoverflow.com/questions/2893500/… Commented Jun 1, 2010 at 22:12
  • @Xavier: from functools import reduce. It's removed from the builtins, it's not phased out completely. Also, what you've heard about its speed is highly inaccurate: it can be much faster or slower than a for loop. Commented Jun 26, 2010 at 14:29

3 Answers 3

14

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

1 Comment

And thus the beauty of using built-ins.
3

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.

Comments

2
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.