Python Set difference_update()

Python Set x.difference_update(y) method remove the elements from calling set x that are present in the set y.

In this tutorial, we will learn the syntax of set.difference_update() method and go through examples covering different scenarios for the arguments that we pass to difference_update() method.

Syntax

The syntax of set.difference_update() is

set.difference_update(other)

where

ParameterDescription
otherA set.
ADVERTISEMENT

Examples

1. Difference of sets x, y, and update x

In the following program, we will take two sets: x, y; and update x with the difference of the sets: x - y.

Python Program

x = {'apple', 'banana', 'cherry'}
y = {'banana', 'mango'}
x.difference_update(y)
print(x)
Try Online

Program Output

{'cherry', 'apple'}

2. Difference of sets x, y; but x and y are disjoint sets

In the following program, we will find the difference of the sets: x - y and update x with the result. But x and y are disjoint sets. There are no common elements between x and y.

Python Program

x = {'apple', 'banana', 'cherry'}
y = {'guava', 'mango'}
x.difference_update(y)
print(x)
Try Online

Program Output

{'banana', 'apple', 'cherry'}

Conclusion

In this Python Tutorial, we learned about Python set method difference_update(). We have gone through the syntax of difference_update() method, and its usage with example programs.