Updates the set by removing the items that are not common
Usage
The intersection_update()
method updates the set by removing the items that are not common to all the specified sets.
You can specify as many sets as you want, just separate each set with a comma.
If you don’t want to update the original set, use intersection() method.
Syntax
set.intersection_update(set1,set2…)
Parameter | Condition | Description |
set1, set2… | Optional | A comma-separated list of one or more sets to search for common items in |
Basic Example
# Remove items that are not common to both A & B
A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}
A.intersection_update(B)
print(A)
# Prints {'red'}
Equivalent Operator &=
You can achieve the same result by using the &=
augmented assignment operator.
A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}
A &= B
print(A)
# Prints {'red'}
intersection_update() Method with Multiple Sets
Multiple sets can be specified with either the operator or the method.
A = {'red', 'green', 'blue'}
B = {'yellow', 'orange', 'red'}
C = {'blue', 'red', 'black'}
# by method
A.intersection_update(B,C)
print(A)
# Prints {'red'}
# by operator
A &= B & C
print(A)
# Prints {'red'}