Python Set intersection_update() method
Python Set intersection_update() method
The set.intersection_update() method in Python removes the items that is not present in both sets.
It is different from the set.intersection() method, because the intersection()method returns a new set, with only the common elements whereas the intersection_update() method removes the unwanted items from the original set.
Syntax
set.intersection_update(set1, set2 ... etc)
Parameter
set1- This parameter represents the set to search for equal items
set2(optional)- This argument signifies the other set to search for equal items. One can compare as many sets as needed, only need to separate the sets with a comma.
Return
None
Example 1
# Python program explaining # the intersection_update() method #initializing set1 set1 = {"mango", "banana", "apple","tomato"} print("Set 1:",set1) # initializing set2 set2 = {"potato", "spinach","Carrot", "apple"} print("Set 2:",set2) # Removing the items that is not present in both sets. set1.intersection_update(set2) print("After intersection_update() method...") print("Updated Set 1:",set1)
Output
Set 1: {'tomato', 'apple', 'mango', 'banana'} Set 2: {'apple', 'Carrot', 'potato', 'spinach'} After intersection_update() method... Updated Set 1: {'apple'}
Example 2
# Python program explaining # the intersection_update() method # initializing set1 set1 = {"a", "b", "c","q","R"} print("Set 1:",set1) # initializing set2 set2 = {"a", "z", "e","q","R"} print("Set 2:",set2) # initializing set3 set3 = {"a", "g", "m","q","R"} print("Set 3:",set3) # removing the items that is not present in three of the sets. . set1.intersection_update(set2, set3) # printing the result print("Updated Set 1:",set1)
Output
Set 1: {'R', 'a', 'b', 'q', 'c'} Set 2: {'R', 'z', 'a', 'q', 'e'} Set 3: {'R', 'a', 'm', 'q', 'g'} Updated Set 1: {'R', 'a', 'q'}
Example 3
# Python program explaining # the intersection_update() method # initializing first set A = {"a", "e", "i"} # initializing second set B = {"o", "u","a"} # initializing third set C = {"u", "z", "a","m"} # initializing fourth set D = {"f","h","l","h","m"} # deleting the element that is not common between Set A and Set B A.intersection_update(B,C,D) # when no element is common print("After the intersection_update() method...") # printing set A print("set A: ",A) # printing set B print("set B: ",B) # printing set C print("set C: ",C) # printing set D print("set D: ",D)
Output
After the intersection_update() method... set A: set() set B: {'o', 'a', 'u'} set C: {'a', 'm', 'z', 'u'} set D: {'l', 'm', 'h', 'f'}