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

# Remove items from A found in B
A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

A.difference_update(B)
print(A)
# Prints {'blue', 'green'}
Set difference

Equivalent Operator -=

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

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

A -= B
print(A)
# Prints {'blue', 'green'}

difference_update() Method with Multiple Sets

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

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

# by method
A.difference_update(B,C)
print(A)
# Prints {'green'}

# by operator
A -= B | C
print(A)
# Prints {'green'}