Set difference_update() Method in Python

Python Set difference_update() Method

The difference_update() method is used to remove elements from a set that are also present in other specified sets. It updates the original set in place and modifies it to contain only the elements that are not present in the specified set(s).

Syntax of the difference_update() method:

set1.difference_update(set2, set3, ...)

Parameters:

  • set1: The original set from which you want to remove elements.
  • set2, set3, ...: The sets whose elements you want to remove from set1.

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

Example:

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

# Removing elements from set1 that are also present in set2
set1.difference_update(set2)

print(set1)  # Output: {1, 2, 3} (set1 is modified to contain elements not present in set2)

In this example, the difference_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 not present in set2 (1, 2, 3).

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

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

# Removing elements from set1 that are present in set2 or set3
set1.difference_update(set2, set3)

print(set1)  # Output: {1, 2} (set1 is modified to contain elements not present in set2 or set3)

In this case, the difference_update() method is used with both set2 and set3 as arguments, and set1 is modified to contain only the elements that are not present in either set2 or set3.