Finding the Intersection of Python Sets: A Practical Use Case

How to Use Python’s Set.Intersection() Method for Market Basket Analysis

My Data Talk
Towards Data Science

Image by Pixabay

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])

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (1)

What are your thoughts?