Set method

set.difference()

Returns a new set with the elements of this set that are not in any of the others. Same as the - operator.

BeginnerEvery example below runs in your browser. Change the code and press Run.

set.difference(*others)

a.difference(b) keeps the elements of a that are not in b. Think of it as "a minus b". Neither set changes.

The order matters: a - b and b - a are different sets. One gives what only a has, the other what only b has.

Use it to find what is missing (required fields not filled in), what is new (today's users that were not here yesterday) or what was removed.

Parameters

ParameterWhat it is
*others
optional
Any number of sets or other iterables whose elements should be taken away.

Return value

A new set.

Examples

1a minus b

Pythoneditable
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a.difference(b))
print(a - b)
print(b - a)
Output
{1, 2}
{1, 2}
{5}

2Which required fields are missing?

Pythoneditable
required = {"name", "email", "country"}
form = {"name": "Ines", "phone": "555"}
missing = required.difference(form)
print("Missing:", sorted(missing))
Output
Missing: ['country', 'email']

Passing a dictionary uses its keys.

3New and gone between two days

Pythoneditable
yesterday = {"ana", "ben", "chloe"}
today = {"ben", "chloe", "dan", "eva"}
print("New:", sorted(today - yesterday))
print("Gone:", sorted(yesterday - today))
Output
New: ['dan', 'eva']
Gone: ['ana']

Common mistakes

Getting the order backwards

a - b is not the same as b - a. Read it as "what does the left one have that the right one does not?". For elements in exactly one of the two, use set.symmetric_difference().

Using - with a list

The - operator needs two sets. The method accepts a list.

Pythoneditable
allowed = {1, 2, 3}
given = [2, 3]
print(allowed.difference(given))
try:
    allowed - given
except TypeError:
    print("TypeError: - needs two sets")
Output
{1}
TypeError: - needs two sets

Questions people ask

How do I subtract one list from another in Python?

If order and duplicates do not matter: set(a) - set(b). To keep order and duplicates, build the set once and then filter: drop = set(b) and [x for x in a if x not in drop].

Is there an in-place version?

Yes: a -= b or a.difference_update(b) remove the elements of b from a.

Spotted a mistake on this page? Tell us