Python Set – intersection_update() Method

Python intersection_update() method is used to update a set with common elements only of all the sets passed in parameter of intersection_update() method.
Python set intersection_update() Method Syntax:
Syntax: set.intersection_update(set1,set2,set3,………..,set n)
Parameters:
- One or more sets
Return: None
Note: To perform this function, we have at least two sets.
Python set intersection_update() Method Example:
Python3
s1 = {1, 2, 3} s2 = {4, 2, 5} s1.intersection_update(s2) # print updated s1 set print("After intersection_update, s1:", s1) |
Output:
After intersection_update, s1: {2}
Example 1: Set intersection_update() operation on multiple sets.
Python3
# declare set1 set1 = {"java", "python", "c/cpp", "html"} # declare set2 set2 = {"php", "html", "java", "R"} # declare set3 set3 = {"java", "python", "ml", "dl"} # declare set4 set4 = {"python", "java", "swift", "R"} # display sets print("set1: {}\nset2: {}\nset3: {}\nset4: {}\n".format(set1, set2, set3, set4)) # perform intersection_update operation on set1 set1.intersection_update(set2, set3, set4) # display the result set print("After intersection_update, set1:", set1) |
Output:
set1: {'c/cpp', 'html', 'python', 'java'}
set2: {'php', 'R', 'html', 'java'}
set3: {'ml', 'dl', 'python', 'java'}
set4: {'swift', 'R', 'python', 'java'}
After intersection_update, set1: {'java'}
Example 2: Using Set intersection_update() where there are no elements in common.
Here we created two sets and there are no common elements between the sets, so the output should be empty.
Python3
# declare set1 set1 = {"java", "python", "c/cpp", "html"} # declare set2 set2 = {"php", "cn", "dbms", "R"} # display sets print(set1, set2) # perform intersection_update operation on # both the sets set.intersection_update(set1, set2) # display the result set print(set1) |
Output:
{'java', 'python', 'c/cpp', 'html'} {'R', 'cn', 'dbms', 'php'}
set()



