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?
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.
The intersection() method returns a set that contains the similarity between two or more sets.
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] .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With