Finding the Intersection of Python Sets: A Practical Use Case
How to Use Python’s Set.Intersection() Method for Market Basket Analysis
A Python set
is a list of unordered, unchangeable*, and unique elements that are placed inside curly braces and separated by commas. Note that when we say it is ‘unchangeable’, we mean that once a set
is created, we can not change an item, but we can still remove items or add new items.
One of the most popular python set
operations is to find the intersection of two or more sets, which can be easily done using Python’s set.intersection()
method. For example, let’s say you have three sets as shown below:
set1={'Storage','Phones','Binders','Accessories','Envelopes'}
set2={'Phones','Envelopes','Binders','Copiers','Tables'}
set3={'Paper','Supplies','Binders','Accessories','Envelopes'}
To find the intersection of set1 and set2, you can do:
s = set1.intersection(set2)
To find the intersection of the three sets, you can do either of the following (notice that in the second code snippet we pass all sets as arguments into set.intersection()
by unpacking the list with the asterisk * operator):
s = set1.intersection(set2,set3)
or:
s = set.intersection(*[set1,set2,set3])