Contents
Python Intersection of Sets
You can find intersection of two or more Python sets using intersection() method.
In this tutorial, we will learn how to use intersection() method to find the set of common elements between two or more sets.
Syntax – intersection()
Following is the syntax of intersection() method.
set_output = set_1.intersection(set_2) # set_1 ∩ set_2
set_output = set_1.intersection(set_2).intersection(set_3) # set_1 ∩ set_2 ∩ set_3
Run Example 1: Intersection of Two Sets in Python
In this example, we shall take two sets and find the intersection of these two sets. Meaning, we find the set containing elements that present in both the sets.
Python Program
#initialize sets
set_1 = {'a', 'b', 'c', 'd'}
set_2 = {'a', 'b', 'd', 'm'}
#intersection of sets
set_output = set_1.intersection(set_2)
print(set_output)
Run Output
{'a', 'd', 'b'}
Example 2: Intersection of More than two sets in Python
intersection() supports chaining and hence you can find intersection of more than two sets in a single line.
In this example, we take three sets and try to find the intersection of these three sets using chaining of intersection() method.
Python Program
#initialize sets
set_1 = {'a', 'b', 'c', 'd'}
set_2 = {'a', 'b', 'd', 'm'}
set_3 = {'d', 'p', 's', 'v'}
#intersection of sets
set_output = set_1.intersection(set_2).intersection(set_3)
print(set_output)
Run Output
{'d'}
'd'
is the only common element between the three sets.
Summary
In this tutorial of Python Examples, we learned how to use intersection() method to find the set of common elements between two or more sets in Python, with the help of well detailed examples programs.