Python Set difference_update() Method

The difference_update() method removes all elements from the set that are also found in other specified sets or iterables. It modifes the original set in place.

Syntax

set1.difference_update(set2, set3, ..., setN)

Parameters

set2, set3, ..., setN: One or more sets or iterables whose elements will be removed from the original set.

Return Value

Returns None. It modifies the original set in place.

Examples

Example 1: Difference update of two sets

a = {1, 2, 3, 4, 5}
b = {4, 5, 6}

a.difference_update(b)
print(a) # Outpt: {1, 2, 3}

Example 2: Difference update of multiple sets

You can pass multiple sets, separated by commas, as arguments to the difference_update() method.

a = {1, 2, 3, 4, 5, 6, 7, 8}
b = {1, 2, 3}
c = {4, 5, 6}

a.difference_update(b, c)
print(a) # Outpt: {7, 8}

Example 3: Difference update with different iterable types

The difference_update() method also accepts iterables of various types, such as lists or tuples, as its arguments.

a = {1, 2, 3, 4, 5, 6, 7, 8}
b = [1, 2, 3] # a list
c = (4, 5, 6) # a tuple

a.difference_update(b, c)
print(a) # Output: {7, 8}

The -= Operator

The -= is a shorthand for performing a set difference update.

For example:

a = {1, 2, 3, 4, 5}
b = {4, 5}

a -= b
print(a) # Output: {1, 2, 3}

The -= operator only works with sets and doesn’t support other iterables like lists or tuples.

Read Also:

Python Set difference() method