Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to find the intersection of multiple sets?

I have a list of sets:

setlist = [s1,s2,s3...] 

I want s1 ∩ s2 ∩ s3 ...

I can write a function to do it by performing a series of pairwise s1.intersection(s2), etc.

Is there a recommended, better, or built-in way?

like image 225
user116293 Avatar asked Mar 29 '10 22:03

user116293


People also ask

How do you find the intersection of multiple sets in Python?

To intersect multiple sets, stored in a list l , use the Python one-liner l. pop(). intersection(*l) that takes the first set from the list, calls the intersection() method on it, and passes the remaining sets as arguments by unpacking them from the list.

Which method is used to find the intersection of two sets?

The intersection() method returns a set that contains the similarity between two or more sets.

How do you find the intersection of two lists?

To perform the intersection of two lists in python, we just have to create an output list that should contain elements that are present in both the input lists. For instance, if we have list1=[1,2,3,4,5,6] and list2=[2,4,6,8,10,12] , the intersection of list1 and list2 will be [2,4,6] .


1 Answers

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.

like image 62
sth Avatar answered Oct 03 '22 07:10

sth