Python Set difference_update()

In this tutorial, you will learn about the Python Set difference_update() method with the help of examples.

The difference_update() method computes the difference between two sets (A - B) and updates set A with the resulting set.


# sets of numbers
A = {1, 3, 5, 7, 9}
B = {2, 3, 5, 7, 11}

# computes A - B and updates A with the resulting set A.difference_update(B)
print('A = ', A) # Output: A = {1, 9}

difference_update() Syntax

The syntax of the difference_update() method is:


Here, A and B are two sets.

difference_update() Parameter

The difference() method takes a single argument:

  • B - a set whose items won't be included in the resulting set

difference_update() Return Value

The difference_update() doesn't return any value.

Example: Python difference_update()

A = {'a', 'c', 'g', 'd'}
B = {'c', 'f', 'g'}

print('A before (A - B) =', A)

print('A after (A - B) = ', A)


Original Set = {'a', 'g', 'c', 'd'}
A after (A - B) =  {'a', 'd'}

In the above example, we have used the difference_update() method to compute the difference between two sets A and B and update set A with the resulting set.

Here, A.difference_update(B) performs A - B and updates set A with value {'a', 'd'}

Did you find this article helpful?