Python Set - intersection_update() Method
The Python intersection_update() method is used to update the set which contains all common elements of two or more sets. This method can take any number of sets or iterables to compute the intersection set and update the original set with intersection set.
The below figure depicts two sets called A = {10, 20, 30, 40, 50, 60} and B = {50, 60, 70, 80}. As 50 and 60 are common elements between A and B, hence intersection of these sets will be {50, 60}. The intersection_update() method can be expressed as:
- A.intersection_update(B) is same as A = AꓵB
- B.intersection_update(A) is same as A = BꓵA
- A.intersection_update(B, C) is same as A = AꓵBꓵC
Syntax
set.intersection_update(iterable(s))
Parameters
iterable(s) |
Optional. specify set(s) or iterable(s) to compute intersection set. |
Return Value
None.
Example: Intersection update using set as an argument
In the example below, two sets called SetA and SetB are taken to compute intersection of these sets and update the original set using python intersection_update() method.
SetA = {10, 20, 30, 40, 50, 60} SetB = {50, 60, 70, 80} # updates SetA with intersection set SetA.intersection_update(SetB) print(SetA) SetA = {10, 20, 30, 40, 50, 60} SetB = {50, 60, 70, 80} # updates SetB with intersection set SetB.intersection_update(SetA) print(SetB)
The output of the above code will be:
{50, 60} {50, 60}
Example: Intersection update using set and iterable as arguments
The intersection_update() method can take any numbers of sets or iterables to compute intersection set and update the original set. In the example below, the intersection_update() method is used with SetA, SetB and ListC to update SetA with a set containing all common elements of these three objects.
SetA = {10, 20, 30, 40, 50, 60} SetB = {40, 50, 90} ListC = {40, 90, 100} SetA.intersection_update(SetB, ListC) print(SetA)
The output of the above code will be:
{40}
❮ Python Set Methods