Python Set difference_update()

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

Example

# 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:

A.difference_update(B)

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)

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

Output

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?