-

Subtraction for numbers, difference for sets. Also the unary negation prefix.

Arithmetic operatorPython 1.0+Live demo
Common call
7 - 2
Returns
difference; int - int stays int
Replaces
{1,2,3} - {2} is set difference
Watch out
strings do NOT support - — use replace to remove
aaLeft operand (minuend).type: number | set · required - bbRight operand (subtrahend).type: number | set · required
number | set

Demo

Live evaluation
Try:
Inputs
afloatleft operand
bfloatright operand
Output
7 - 2
5

Plain numeric subtraction — results can go negative, and floats show their stored binary values (0.3 - 0.1 is 0.19999999999999998).

Operands

NameTypeRequiredDescription
anumber | setyesLeft operand (minuend).
bnumber | setyesRight operand (subtrahend).

Return value

number | setThe difference of two numbers — or, for sets, the elements of a not in b.

Common patterns

Deltas and distances
Wrap in abs() when direction does not matter.
delta = after - before
distance = abs(a - b)
Set difference
What is in a but not in b.
missing = required - provided

Examples

1. Numbers
7 - 2
Returns
5
2. Negative result
2 - 7
Returns
-5
3. Set difference
{1, 2, 3} - {2}
Returns
{1, 3}
4. Unary minus
-(3 + 4)
Returns
-7

Pitfalls

1. No string subtraction
Removing a substring is replace, not minus.
Raises
"hello.txt" - ".txt"
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Fix
"hello.txt".removesuffix(".txt")
'hello'
2. Float drift
Binary floats make simple-looking differences inexact.
Surprising
0.3 - 0.1
0.19999999999999998
Exact decimals
from decimal import Decimal
Decimal("0.3") - Decimal("0.1")
Decimal('0.2')

When to use

Use it
  • Numeric differences and deltas
  • Set difference between collections of unique items
Reach for something else
  • Removing substrings → str.replace / removesuffix
  • Removing list items → list.remove or a comprehension
  • Money math → decimal.Decimal

Notes

Complexity
O(1) numbers; O(len(a)) sets
Return
new value; operands untouched
CPython impl
Objects/abstract.c :: PyNumber_Subtract → __sub__ / __rsub__
Memory
Set difference allocates a new set
Thread-safe
Yes — operands are not mutated

FAQ

Not with -; convert to sets (losing order/duplicates) or use a comprehension to keep order.

[x for x in a if x not in set(b)]

History

1.0
Core operator from the beginning.