Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Operator -

Subtracts the right operand from the left.

Version: Python 3.14; repository image, production runtime not attested

Syntax

left - right

Subtracts the right operand from the left.

For numeric measurements the difference preserves direction, so exchanging the operands reverses its sign. Mixed integer and floating-point inputs are supported.

Operand types can implement forward or reflected subtraction. Both sets and numbers accept the same spelling, but a set difference requires compatible set operands; subtracting a list from a set fails.

For sets, subtraction keeps precisely the members absent from the right operand.

Syntax

left - right

__sub__, __rsub__ · TypeError

Worked example

5 - 8 → -3
{1, 3} - {3, 5} → {1}
{1} - [1] → TypeError

set -

For numeric or custom operands, a strict right-hand subclass with a different reflected subtraction method gets priority. If both subtraction methods return NotImplemented, the operator raises TypeError. For sets, A - B retains members of A absent from B. Reversing the operands can change both the members and result type, here {2, 9} versus frozenset({7}). The inputs remain intact, and the difference method also accepts a list.

available={2,4,9}
used=frozenset({4,7})
assert available - used == {2,9}
assert used - available == {7} and type(used-available) is frozenset
assert available=={2,4,9} and available.difference([4,7])=={2,9}

Examples

print(12 - 17)
print(sorted({2, 4, 9} - {4, 7}))

Result

-5
[2, 9]

For sets, subtraction keeps precisely the members absent from the right operand.

Sources