difference(*others) builds a new set with the items of the set that do not appear in any of the iterables you pass. The original set is not changed.
Order matters: a.difference(b) keeps what only a has, while b.difference(a) keeps what only b has. With no arguments, you simply get a copy of the set.
set.difference() is an instance method of the built-in set type: call it on a set with dot notation, such as borrowed.difference(...). No import is needed.
Syntax
Pass one or more iterables to subtract, and keep the returned set in a variable.
Returns {1, 3}: the items of the set that are not in the argument.
{1, 2, 3}.difference([1], (3,))
Returns {2}: items found in any argument are removed.
{1, 2}.difference({1, 2, 3})
Returns set(): nothing of the first set is left, because the argument contains it all.
a - b is a shortcut for a.difference(b), but only between two sets. To remove the items from the existing set instead of making a new one, use difference_update().
Method signatures
python
set.difference(*others)
# returns: a new set with the items of the set that are in none of the iterables
# 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. An item is dropped if it appears in any of them.
Return Value
Return Value
Description
set
A new set with the remaining items. It is empty (set()) when everything was subtracted.
Python Examples
Example 1 — List the Library Books Not Yet Returned
Subtract the returned books from the borrowed ones, then swap the order.