To subtract in Python, put the minus operator between two values: 20 - 7 returns 13. Type it straight into the Python interpreter, or store the answer in a variable with result = a - b and show it with print(result). Everything here applies to Python 3 on Windows, macOS and Linux, and every example uses only the standard library except one short NumPy note.
What you need first
You need Python 3 installed and a way to run it. A few terms come up often:
- Interpreter: the program that runs Python. On a Mac or Linux computer you start it in Terminal with
python3. On Windows the recommended command ispy. IDLE, the simple editor that ships with Python, also gives you an interactive window. - Operand: a value on either side of an operator. In
20 - 7, the operands are 20 and 7. - int and float: whole numbers such as
20are integers, and numbers with a fractional part such as2.5are floats.
Subtract two numbers with the minus operator
- Open Terminal (Mac or Linux) or a Command Prompt or PowerShell window (Windows) and start Python with
python3orpy. You will see the>>>prompt. - Type
20 - 7and press Enter. Python prints13on the next line. - Swap the order to see that it matters:
7 - 20prints-13. The value after the minus sign is always taken away from the value before it. - Save values in variables so you can reuse them: type
total = 50, thenspent = 18, thenleft = total - spent. - Type
print(left). The output is32. In a saved.pyfile you always needprint(), because only the interactive prompt echoes results automatically.
Mixing types is allowed. When one operand is a float, Python converts the other to a float too, so 10 - 2.5 gives 7.5. Two integers give an integer.
Other ways to write a subtraction
The plain operator covers most jobs. Reach for these when the situation calls for them.
Shrink a variable with -=
x -= 18 means the same as x = x - 18. It is handy inside loops, such as counting down stock or a balance.
Subtract several values at once
You can chain the operator: 100 - 30 - 20 - 15 returns 35, working left to right. When the amounts sit in a list, subtract their total instead: 100 - sum([30, 20, 15]) gives the same answer and stays readable as the list grows.
Use a function when code expects one
The operator module provides operator.sub(a, b), which returns a - b. It is useful when another tool, such as functools.reduce, needs a function rather than an operator. Writing your own def subtract(a, b): return a - b works the same way.
Get a distance that is never negative
Wrap the expression in abs() when only the size of the gap matters: abs(4 - 9) returns 5.
Subtracting money, dates, sets and lists
The minus sign also works on several non-number types, each with its own rules.
| What you subtract | How | Result |
|---|---|---|
| Money (exact decimals) | Decimal('0.30') - Decimal('0.10') | Decimal('0.20') |
| Two dates | date(2026, 12, 25) - date(2026, 11, 19) | timedelta(days=36) |
| Sets | {1, 2, 3, 4} - {2, 4} | {1, 3} |
| Lists | [i for i in a if i not in b] | A new list without b’s items |
| Item counts | Counter(a) - Counter(b) | Counts above zero only |
A few details are worth knowing. Build Decimal values from strings, not floats, or the float’s tiny error comes along with it. Subtracting two dates or datetimes gives a timedelta; read its .days attribute for a day count, or call .total_seconds() for the full duration. Sets drop duplicates and ordering, so use the list comprehension when both matter. A Counter subtraction removes one copy per match, while Counter.subtract() keeps zero and negative counts. If you work with NumPy arrays, the same - operator subtracts element by element, so np.array([10, 20, 30]) - 5 gives [ 5 15 25].
Worked example: a weekly budget script
Priya wants to know what is left of a weekly budget after typing in what she spent. Because input() always returns text, the script converts it with Decimal before subtracting and catches anything that is not a number.
from decimal import Decimal, InvalidOperation
budget = Decimal("150.00")
entry = input("Amount spent: ")
try:
spent = Decimal(entry)
except InvalidOperation:
print("Please type a number such as 42.75")
else:
left = budget - spent
print("Left this week:", left)
if left < 0:
print("Over budget by", abs(left))
Typing 42.75 prints Left this week: 107.25. Typing 162.40 prints Left this week: -12.40 followed by Over budget by 12.40. Typing lots prints the help message instead of crashing.
Errors and odd results
- TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’. You subtracted text, usually straight from
input(). Convert first withint(),float()orDecimal(). The same error with'list' and 'list'means lists do not support-; use the list comprehension above. - ValueError: invalid literal for int().
int("12.50")fails because the text is not a whole number. Usefloat()orDecimal(), or wrap the conversion intry/except. - 0.3 – 0.1 shows 0.19999999999999998. Floats are stored in binary and many decimal fractions cannot be represented exactly, as the floating-point chapter of the Python tutorial explains. Format the output with
round(x, 2)orf"{x:.2f}", compare withmath.isclose(), or useDecimalfor money. Rounding only changes what you see, not the stored value. - SyntaxError: invalid character ‘–’ (U+2013). Recent Python 3 versions show this message when code copied from a web page or word processor contains an en dash instead of the keyboard hyphen. Delete it and type
-again. - -3**2 returns -9. Powers are calculated before the minus sign, so Python reads it as
-(3**2). Write(-3)**2to get 9. Multiplication also goes first:50 - 5*6is 20. - TypeError when subtracting datetimes. One value has a time zone and the other does not. Make both naive or both time-zone aware.
Check the answer and fix mistakes
Add the result back to what you took away: if left + spent == total prints True, the subtraction is right (use math.isclose() for floats). Run type(left) when a result looks strange, since an unexpected str or float explains most surprises. A wrong answer in a variable is fixed by assigning it again with the correct expression. If you used -= by mistake, add the same amount back with +=.
Quick answers about Python subtraction
Does subtracting change the original variable?
No. total - spent creates a new value and leaves both variables alone. Only an assignment such as total -= spent changes total.
Can I subtract True or False?
Technically yes, because booleans are a subtype of integers and act like 1 and 0, but the Python documentation discourages relying on it. Convert with int() to make the intent clear.
Is there a shortcut for reusing the last answer?
At the interactive prompt, the underscore _ holds the last printed result, so _ - 5 continues a calculation. It does not work in saved scripts.
How is this different in other languages?
The minus sign looks the same, but conversions differ. JavaScript quietly turns some text into numbers, which is covered in subtracting values in JavaScript, and databases have their own date rules, explained in subtraction in SQL queries.
Next, try changing the budget script to read several amounts in a loop and subtract each one with -=. If you only need a one-off difference in a spreadsheet instead, the Excel subtraction formulas may be quicker.