Summary: in this tutorial, you’ll learn about the Python set intersection and how to use it to intersect two or more sets.
TL;DR #
In Python, you can use the set intersection() method or set intersection operator (&) to intersect two or more sets:
new_set = set1.intersection(set2, set3)
new_set = set1 & set2 & set3The intersection() method and & operator have the same performance.
Introduction to Python set intersection #
When intersecting two or more sets, you’ll get a new set consisting of elements that exist in all sets.
Suppose that you have two following sets s1 and s2:
s1 = {'Python', 'Java','C++'}
s2 = {'C#', 'Java', 'C++' }Code language: JavaScript (javascript)The intersection of these two sets returns a new set that contains two elements 'Java' and 'C++':
s = {'Java', 'C++'}Code language: JavaScript (javascript)… because they’re the only elements that exist in both sets.
The following Venn diagram illustrates the intersection of two sets s1 and s2: