Python Set Intersection_Update():
The intersection_update() method updates the source set to reflect the intersection of multiple sets. Hence, the content of original set is modified.
Method signature
The signature for the intersection_update()
method is as shown below. Here, the intersection of set A with zero or more sets, given in the parameter, is performed here and the result is stored in set A.
C=A.intersection_update(B1,B2,..)
Method parameters and return type
- The intersection_update() method takes zero or more sets as a parameter. Furthermore, it does not update the set in absence of any parameter.
- However, It doesn’t return anything.
Python Set intersection_update Examples:
Example 1: In this example, let us take a set A and set B and set C with a set of numbers.
#Initializing the Set
A={18,13,48,36,65}
B={22,36,54,13,5}
C={35,42,56}
#Printing set A and set B
print("Before set A is ",A)
print("Set B is ",B)
# Using intersection_update
A.intersection_update(B)
#Printing a result
print("Updated set A is ",A)
print("Now, set B is ",B)
# If no parameter is passed it doesn't update
C.intersection_update()
#Printing a result
print("No parameter passed in method",C)
Output
Before set A is {65, 36, 13, 48, 18}
Set B is {36, 5, 13, 54, 22}
Updated set A is {36, 13}
Now, set B is {36, 5, 13, 54, 22}
No parameter passed in method {56, 42, 35}
Example 2: In this case, let us consider a set S containing names of the students nominated for best student of the year. Similarly, Set Comp and Sport contains name of winners in competition and sport. Suppose if we want to find the student who has won medal in both competition and sports. Here, We have to use intersection_update method. Furthermore, if set does not contain an element present in all three, it returns an empty set
#Initializing the Set
S={"Sam", "Jimmy","Tom","Keya","Ram"}
comp={"Ram", "Jimmy", "Keya"}
sport={"Kim", "Sam","Keya", "Tom"}
#Using intersection_update method
S.intersection_update(comp,sport)
#Printing a set
print("Student who secured medal in competition and sport is ",S)
Output
Student who secured medal in competition and sport is {'Keya'}
Example 3: In this example, let us demonstrate the intersection_update() method on a mixed set. Presently, there is no common data elements in set c1 with all the other sets. Hence, intersection_update will update the Set c1 as an empty set.
#Initializing the Set
c1={"Kim",25,8.5}
c2={"Sam",25,10}
c3={"Raj",22,1.5}
c4={"Roy",22,14}
# Using intersection_update method
c1.intersection_update(c2,c3,c4)
c3.intersection_update(c4)
# Printing a Set
print ("Result of intersection_update in c1",c1)
print ("Result of intersection_update in c3",c3)
Output
Result of intersection_update in c1 set()
Result of intersection_update in c3 {22}
Conclusion
The intersection_update() method selects the elements that are common with other sets in the parameter and updates the set which calls this method.
References
Happy Learning 🙂