Python Set difference_update() Method

Updates the set by removing items found in other sets

Usage

The difference_update() method updates the set by removing items found in specified sets.

You can specify as many sets as you want, just separate each set with a comma.

If you don’t want to update the original set, use difference() method.

Syntax

set.difference_update(set1,set2…)

Python set difference_update() method parameters
ParameterConditionDescription
set1, set2…OptionalA comma-separated list of one or more sets to find differences in

Basic Example

Example: Remove items from A found in B

A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

A.difference_update(B)
print(A)

Output:

{'blue', 'green'}

Venn Diagram:

Set difference

Equivalent Operator -=

You can achieve the same result by using the -= augmented assignment operator.

Example:

A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

A -= B
print(A)

Output:

{'blue', 'green'}

difference_update() Method with Multiple Sets

Multiple sets can be specified with either the operator or the method.

Example:

# by method
A = {'red', 'green', 'blue'}
B = {'yellow', 'orange', 'red'}
C = {'blue', 'red', 'black'}

A.difference_update(B,C)
print(A)
# by operator
A = {'red', 'green', 'blue'}
B = {'yellow', 'orange', 'red'}
C = {'blue', 'red', 'black'}

A -= B | C
print(A)

Output:

{'green'}