Python set Method - difference_update()

The difference_update() method in Python is used to remove the elements of a second set from the first set. The method modifies the original set in place and does not return anything.

The syntax for the difference_update() method is as follows:

set1.difference_update(set2)
Source‮i.www:‬giftidea.com

Here, set1 is the set from which we need to remove the elements of set2. The method removes the elements of set2 from set1 and modifies set1 in place.

Example:

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

# Removing the elements of set2 from set1
set1.difference_update(set2)

# Displaying the modified set
print(set1)   # Output: {1, 2}

In the above example, the difference_update() method is used to remove the elements of set2 from set1. The original set set1 is modified in place and the output shows that it now contains only the elements {1, 2}. If there are no common elements between the sets, the difference_update() method has no effect. It is important to note that the difference_update() method modifies the original set in place, so if you want to preserve the original set, you should make a copy of it before using the method.