Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python Set – intersection_update() Function

  • Last Updated : 05 Nov, 2021

Python intersection_update() function is used to get the elements that are present in all the given sets. It will remove the elements which are not present in all the sets.

Syntax:

set.intersection_update(set1,set2,set3,...........,set n)

Where, set1, set2, are the input sets. It can take any number of sets.

Note: To perform this function we have at least two sets.

Example: Python program to define two sets with string elements.

Python3




# declare set1
set1 = {"java", "python", "c/cpp", "html"}
  
# declare set2
set2 = {"php", "html", "java", "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:

{‘c/cpp’, ‘python’, ‘html’, ‘java’} {‘php’, ‘R’, ‘html’, ‘java’}

{‘html’, ‘java’}

Example2: 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, set2, set3, set4)
  
# perform intersection_update operation on
# all the sets
set.intersection_update(set1, set2, set3, set4)
  
# display the result set
print(set1)


Output:

{‘java’, ‘html’, ‘c/cpp’, ‘python’} {‘java’, ‘php’, ‘html’, ‘R’} {‘java’, ‘ml’, ‘dl’, ‘python’} {‘python’, ‘java’, ‘swift’, ‘R’}

{‘java’}

Example 3:

Here we created two sets and there are no common elements in both sets so the output should be empty. Among all the sets no elements are common, so the output is an empty set.

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()


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!