Python set Method - intersection_update()
The intersection_update()
method in Python is used to update a set with the intersection of itself and one or more other sets. The method modifies the original set in place, and returns None
.
The syntax for the intersection_update()
method is as follows:
set1.intersection_update(set2, set3, ...)Souri.www:ecgiftidea.com
Here, set1
is the set that needs to be updated, and set2
, set3
, etc. are the sets that are used to compute the intersection. The method modifies set1
in place to contain only the elements that are common to itself and all the other sets.
Example:
# Creating three sets set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6} set3 = {4, 5, 6, 7} # Updating set1 with the intersection of itself and the other sets set1.intersection_update(set2, set3) # Displaying the sets after intersection update print(set1) # Output: {4} print(set2) # Output: {3, 4, 5, 6} print(set3) # Output: {4, 5, 6, 7}
In the above example, the intersection_update()
method is used to update set1
with the intersection of itself, set2
, and set3
. Since the intersection of these sets is {4}
, set1
is modified to contain only the element 4
. The original sets and the updated set1
are printed to show their contents.
If any of the sets used to compute the intersection is empty, the intersection will also be empty:
# Creating an empty set and two non-empty sets empty_set = set() set1 = {1, 2, 3} set2 = {3, 4, 5} # Updating empty_set with the intersection of the sets empty_set.intersection_update(set1, set2) # Displaying the sets after intersection update print(empty_set) # Output: set() print(set1) # Output: {1, 2, 3} print(set2) # Output: {3, 4, 5}
In this case, since empty_set
is empty, the intersection of the sets set1
and set2
is also empty. Therefore, empty_set
remains empty after the intersection update.