The Set intersection() method finds the common elements between two or more sets. It returns a new set that contains only the items that exist in all the sets being compared.
Syntax
my_set.intersection(set1, set2, ...)intersection() Parameters
Python Set intersection() method parameters:
| Parameter | Condition | Description |
|---|---|---|
set1, set2, ... |
Optional | A comma-separated list of one or more sets to find common items in |
intersection() Return Value
Python Set intersection() method returns a new set containing the common elements of all the sets being compared.
Examples
Example 1: Common Elements of Two Sets with intersection() method
A = {'Tom', 'Anna', 'David'}
B = {'David', 'Tom'}
result = A.intersection(B)
print(result) # Output: {'David', 'Tom'}output
{'David', 'Tom'}Example 2: Intersection between Multiple Sets
The intersection() method allows to compute the common elements between multiple sets:
A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
B = {3, 4, 5, 6, 7}
C = {6, 7, 8, 9, 10}
result = A.intersection(B, C)
print(result) # Output: {6, 7}output
{6, 7}Example 3: Intersection between a Set and a List
You can also pass iterables like list: intersection() first converts the iterables to sets and then computes the intersection.
For example:
A = {'a', 'e', 'i', 'o', 'u'}
B = ['d', 'e', 'f']
print(A.intersection(B)) # Output: {'e'}output
{'e'}Example 4: Intersection between a Set and a Tuple
You can also pass iterables like tuple: intersection() first converts the iterables to sets and then computes the intersection.
For example:
A = {'a', 'e', 'i', 'o', 'u'}
B = ('d', 'e', 'f')
print(A.intersection(B)) # Output: {'e'}output
{'e'}Example 5: Intersection between a Set and a Dictionary
You can also pass iterables like dictionary: intersection() first converts the iterables to sets and then computes the intersection.
For example:
A = {'a', 'e', 'i', 'o', 'u'}
B = {1: 'd', 2: 'e', 3: 'f'}
C = {'d': 1, 'e': 2, 'f': 3}
print(A.intersection(B)) # Output: set()
print(A.intersection(C)) # Output: {'e'}output
set()
{'e'}Example 6: Intersection between a Set and a String
You can also pass iterables like string: intersection() first converts the iterables to sets and then computes the intersection.
For example:
A = {'a', 'e', 'i', 'o', 'u'}
B = 'def'
print(A.intersection(B)) # Output: {'e'}output
{'e'}Equivalent Operator & for intersection()
Set intersection can be performed with the & operator as well, providing an alternative to the intersection() method.
A = {1, 2, 3, 4, 5}
B = {3, 4, 5, 6, 7}
print(A.intersection(B)) # Output: {3, 4, 5}
print(A & B) # Output: {3, 4, 5}output
{3, 4, 5}
{3, 4, 5}Of course, you can use the & operator with multiple sets:
A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
B = {3, 4, 5, 6, 7}
C = {6, 7, 8, 9, 10}
print(A.intersection(B, C)) # Output: {6, 7}
print(A & B & C) # Output: {6, 7}output
{6, 7}
{6, 7}