Contents
Python Set intersection() method
Python set intersection() method finds and returns the intersection of the two sets.
In this tutorial, you will learn the syntax and usage of Set intersection() method, with examples.
Syntax of Set intersection()
The syntax to call intersection() method is
set.intersection(s)
Parameters
Set intersection() method takes one parameter.
Parameter | Description |
---|---|
s | Required A set object. |
Return value
intersection() method returns a set object.
Usage
The following statement shows how the intersection of two sets set_1 and set_2 is done using set.intersection() method, and store the result in set_output.
# Set_1 ∩ set_2
set_output = set_1.intersection(set_2)
We can also chain the intersection() method, to find the intersection of more than two sets in a single statement, as shown in the following code.
# Set_1 ∩ set_2 ∩ set_3
set_output = set_1.intersection(set_2).intersection(set_3)
Examples
1. Finding intersection of two sets in Python
In this example, we shall take two sets in set_1 and set_2. We have to find the intersection of these two sets.
Call intersection() method on set_1 object, and pass set_2 object as argument. Store the returned value in set_output.
set_output contains the intersection of elements from the two sets: set_1 and set_2.
Python Program
# Take two sets
set_1 = {'a', 'b', 'c', 'd'}
set_2 = {'a', 'b', 'd', 'm'}
# Find the intersection of sets
set_output = set_1.intersection(set_2)
print(set_output)
Run Code CopyOutput
{'a', 'd', 'b'}
2. Finding intersection of three sets in Python
Set intersection() method supports chaining, and therefore, you can find the 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 by chaining the intersection() method.
Python Program
# Take three sets
set_1 = {'a', 'b', 'c', 'd'}
set_2 = {'a', 'b', 'd', 'm'}
set_3 = {'d', 'p', 's', 'v'}
# Find the intersection of sets
set_output = set_1.intersection(set_2).intersection(set_3)
print(set_output)
Run Code CopyOutput
{'d'}
'd' is the only common element between the three sets.
Summary
In this Python Set Tutorial, we learned how to use intersection() method to find the intersection operation of given two or more sets in Python, with the help of well detailed examples.