difference_update(*others) deletes from the set every item that appears in any of the iterables you pass. Items that are not in the set are simply ignored. The set is changed in place.
It does the same job as difference(), but instead of returning a new set it overwrites the original and returns None.
set.difference_update() is an instance method of the built-in set type: call it on a set with dot notation, such as subscribers.difference_update(...). No import is needed.
Syntax
Pass one or more iterables to subtract, and call it on its own line, because the return value is always None.
python
s.difference_update(iterable)
s.difference_update(iterable1, iterable2)
s -= other_set
Call
What it does
{1, 2, 3}.difference_update({2})
Returns None; the set becomes {1, 3}.
{1, 2, 3}.difference_update([1], (3,))
Returns None; the set becomes {2}. Several iterables can be subtracted at once.
{1, 2}.difference_update(5)
Raises TypeError: an int is not iterable.
s -= other has the same effect, but needs another set on the right. To remove a single item use discard() or remove(); to keep the original items and get a new set, use difference().
Method signatures
python
set.difference_update(*others)
# returns: None; every item found in any iterable is no longer in the set
# raises: TypeError if an argument is not iterable or an item is unhashable
Parameters
Parameter
Description
*others
Zero or more iterables: set, list, tuple, string, range, and so on. Items found in any of them are removed from the set.
Return Value
Return Value
Description
None
Always None. The set itself is smaller; it is empty (set()) if everything was removed.
Python Examples
Example 1 — Remove Unsubscribed Emails From a Mailing List
Subtract a list from a set, including an address that was never subscribed.