Best way to find the intersection of multiple sets? Best way to find the intersection of multiple sets? python python

Best way to find the intersection of multiple sets?


From Python version 2.6 on you can use multiple arguments to set.intersection(), like

u = set.intersection(s1, s2, s3)

If the sets are in a list, this translates to:

u = set.intersection(*setlist)

where *a_list is list expansion

Note that set.intersection is not a static method, but this uses the functional notation to apply intersection of the first set with the rest of the list. So if the argument list is empty this will fail.


As of 2.6, set.intersection takes arbitrarily many iterables.

>>> s1 = set([1, 2, 3])>>> s2 = set([2, 3, 4])>>> s3 = set([2, 4, 6])>>> s1 & s2 & s3set([2])>>> s1.intersection(s2, s3)set([2])>>> sets = [s1, s2, s3]>>> set.intersection(*sets)set([2])


Clearly set.intersection is what you want here, but in case you ever need a generalisation of "take the sum of all these", "take the product of all these", "take the xor of all these", what you are looking for is the reduce function:

from operator import and_from functools import reduceprint(reduce(and_, [{1,2,3},{2,3,4},{3,4,5}])) # = {3}

or

print(reduce((lambda x,y: x&y), [{1,2,3},{2,3,4},{3,4,5}])) # = {3}