Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Set difference: the `-` operator

The `-` operator builds a new set from elements found in the left set but not the right one. With integers, the same operator performs arithmetic subtraction.

Version: Python 3.12

Syntax

a - b

In Python 3.12, a - b computes set difference when a and b are sets. It creates a new set containing only elements that are in a and not in b, leaving both operands unchanged. The order of the operands matters: b - a can give a different result. With integers, the same operator subtracts numbers: 3 - 1 gives 2, not a set.

Either operand can be a set or a frozenset, and the result has the type of the left operand. For a built-in set a, a - [3] raises TypeError because a list is not a set. Use a.difference([3]) to compute the difference with a list. difference() accepts non-set iterables, but it can raise TypeError if the iterable yields an unhashable element, such as a list.

When a is a set, a -= b changes the existing set in place, unlike a - b. Sets have no defined element order. Here, sorted() returns a sorted list for display; the difference itself is still a set.

Examples

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

print(sorted(a - b))
print(sorted(b - a))
print(3 - 1)

Result

[1, 2]
[4]
2

Both sets contain `3`, so it appears in neither difference. The first two lines print sorted lists; the third shows the result of integer subtraction.

Related lessons

  • Python · Lesson 18 · Basic · Version: 3

Sources