In the last tutorial, we have discussed the intersection() method that returns a new set with the elements that are common to all Sets. In this tutorial, we will discuss the intersection_update() method that does not return anything, however it updates the calling Set with the intersection Set. For example calling this method like this X.intersection_update(Y)
would update the Set X with the X ∩ Y
.
Set intersection_update() method Syntax
X.intersection_update(Y)
This will update the Set X with X ∩ Y (elements that are common to both the Sets X and Y).
Parameter: This method accepts Sets as parameters.
Return value: It doesn’t return anything, it just updates the calling Set.
Python Set intersection_update() method example
In the following example we have two sets X and Y. Here we are calling the method like this: X.intersection_update(Y), this will update the Set X with the intersection values of X and Y.
# Set X X = {1, 2, 3, 4, 5} # Set Y Y = {4, 5, 6, 7} # X will have the elements of X ∩ Y X.intersection_update(Y) # display X print("X is:", X) # display Y print("Y is:", Y)
Output:
Set intersection_update() with more than one Parameters
In the following example we have three Sets X, Y and Z. Here we are passing more than one parameters to the intersection_update() method. To find the intersection between more than two sets we can pass the additional sets in the intersection_update() method as shown in the following example.
# Set X X = {1, 2, 3, 4, 5} # Set Y Y = {4, 5, 6, 7} # Set Z Z = {5, 6, 7, 8, 9} # X will have the elements of X ∩ Y ∩ Z X.intersection_update(Y, Z) # display X print("X is:", X) # display Y print("Y is:", Y) # display Z print("Z is:", Z)
Output:
Leave a Reply