Set intersection_update() Method in Python

Python Set intersection_update() Method

The intersection_update() method is used to modify the original set, keeping only the elements that are common to the original set and other specified sets. It updates the original set in place and removes any elements that are not present in all the specified sets.

Syntax of the intersection_update() method:

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

Parameters:

  • set1: The original set on which you want to perform the intersection operation.
  • set2, set3, ...: The sets with which you want to find the common elements.

Note that you can provide multiple sets as arguments to the intersection_update() method.

Example:

# Creating two sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Updating set1 to keep only the common elements between set1 and set2
set1.intersection_update(set2)

print(set1)  # Output: {4, 5} (set1 is modified to contain only common elements with set2)

In this example, the intersection_update() method is applied to set1, and it takes set2 as an argument. After the operation, set1 is modified to contain only the elements that are common with set2 (4, 5).

You can also provide multiple sets to the intersection_update() method:

# Creating three sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set3 = {3, 4, 6}

# Updating set1 to keep only the common elements among set1, set2, and set3
set1.intersection_update(set2, set3)

print(set1)  # Output: {4} (set1 is modified to contain only the element common to all three sets)

In this case, the intersection_update() method is used with both set2 and set3 as arguments, and set1 is modified to contain only the element that is present in all three sets (4). Elements 5, 2, and 1 are removed because they are not common to all three sets.