Python Operator Precedence and Associativity
Syntax vs. semantics
Each construct below has two parts, and it is worth keeping them apart:
- Syntax — what makes the expression a valid Python program.
- Semantics — what the expression evaluates to.
A syntax rule is always of the form “if x and y are valid Python expressions, then this is a valid Python expression” — which is what makes arbitrarily long arithmetic legal without a separate rule for every length. Precedence and associativity do not take this shape; they are plain rules.
Constants and brackets
- A constant (e.g.
2) is the most basic expression. - If
xis a valid expression then(x)is also a valid expression — bracketed expressions get evaluated first. Whitespace inside brackets is ignored, and brackets can nest arbitrarily (((2))). - An unmatched closing bracket (
2)) is aSyntaxError.
Negation and affirmation
- If
xis a valid expression then+xand-xare valid expressions. +xis equivalent to multiplyingxby1;-xis equivalent to multiplyingxby-1.- These can be chained (
--3is3,+-+-+-3is-3), but a trailing operator with nothing after it (3+) is aSyntaxError. - Style: write
3 + -3rather than3 + - 3, and2 - -2rather than2 - - 2— group the sign with the number it belongs to.
Arithmetic operators
If x and y are valid expressions, then all of the following are valid expressions, evaluated according to the rules of math:
| Operator | Meaning |
|---|---|
x + y |
Addition |
x - y |
Subtraction |
x * y |
Multiplication |
x / y |
Division |
x // y |
Integer (floor) division |
x % y |
Remainder |
x ** y |
Exponentiation |
Order of operations
1 + 2 * 3 + 4 evaluates to 11, not 13, so * must happen before +. Without an order of operations that expression is ambiguous.
From highest to lowest precedence:
| Operator | Description |
|---|---|
() |
Parenthesis |
** |
Exponents |
-x, +x |
Negation, Affirmation |
*, /, //, % |
Multiplication, Division, Integer Division, Remainder |
+, - |
Addition, Subtraction |
Two consequences of the middle row that catch people out: exponentiation outranks unary minus, and unary minus outranks multiplication. So 2 * -3 is 2 * (-3) = -6, and 1 - -2 * -3 - 4 is 1 - ((-2) * (-3)) - 4 = -9.
*, /, //, and % share a precedence level, as do + and - — so the table by itself still leaves ties. See Associativity below.
Associativity
An order of operations alone doesn’t remove all ambiguity — e.g. 1 - 2 + 3 needs a rule for whether it means (1 - 2) + 3 or 1 - (2 + 3). Python evaluates 1 - 2 + 3 as 2, matching (1 - 2) + 3 rather than 1 - (2 + 3) = -4, so +/- are left-associative.
Operators of equal precedence are left-associative in general, except exponentiation (**), which is right-associative:
3 * 1 // 2=(3 * 1) // 2=1, whereas3 * (1 // 2)=0(left-associative*///)2 ** 1 ** 0=2 ** (1 ** 0)=2, whereas(2 ** 1) ** 0=1(right-associative**)
In general, if # and @ are operators of equal precedence, a # b @ c = (a # b) @ c (left-associative case).
Putting both rules on one expression
The exam question x = 35 * 2 % 5 ** 2 needs precedence and associativity to settle, which is why it is the one worth working slowly.
Figure 1: Fully bracketing x = 35 * 2 % 5 ** 2, one rule at a time, to reach (35 * 2) % (5 ** 2) = 70 % 25 = 20. Each step boxes the tokens it brackets and names the rule in purple on the right; magenta marks the answer. Step one is precedence: ** outranks everything else present. Step two is associativity: * and % sit on the same row of the table, so the tie is broken left-first. After that no choices remain.
The other exam question resolves by precedence alone: 2 ** 3 % 5 - 1 is ((2 ** 3) % 5) - 1 = (8 % 5) - 1 = 3 - 1 = 2.
The tempting wrong answers to 35 * 2 % 5 ** 2 (0, 140 and 70) are a good check on the table. Evaluating strictly left to right, ignoring precedence altogether, gives ((35 * 2) % 5) ** 2 = 0 ** 2 = 0. Letting % bind first, then **, and leaving * until last gives 35 * ((2 % 5) ** 2) = 35 * 4 = 140. And 70 is just 35 * 2 with the rest of the expression dropped.
Division and floats
/always returns afloat, even when the division is exact (4 / 2is2.0, not2) —type(2)isint,type(2.0)isfloat.1 / 3gives an approximate result (0.3333333333333333) since floats have finite precision.1 / 0raisesZeroDivisionError;1 / float('inf')is0.0.6 / 2 * (1 + 2)is9.0— brackets first, then/and*left to right, and the/makes the whole result a float.
Exponentiation edge cases
2 ** 3is8(int);2 ** 3.0is8.0(float) — a float exponent/base produces a float result.2 ** -1is0.5.2 ** 0and0 ** 0are both1.
Warning: ^ is not exponentiation
The caret ^ is Python’s bit-wise xor operator, not exponentiation — e.g. 2 ^ 3 is 1 and 4 ^ 1 is 5. Using ^ where you meant ** does not raise an error, so this mistake can silently produce wrong results.
Integer division (the division algorithm)
For positive integers x and y, there is a unique quotient q and remainder r (with 0 <= r < y) satisfying x = q * y + r — “grade school” division. E.g. for x = 17, y = 3: 17 = 5 * 3 + 2, so 17 // 3 is 5 (the quotient) and 17 % 3 is 2 (the remainder), and 3 * (17 // 3) + (17 % 3) == 17.
The division algorithm can be computed directly (repeated subtraction) or recursively:
def remainder(x: int, y: int) -> int:
ans = x
while ans >= y:
ans = ans - y
return ansdef remainder(x: int, y: int) -> int:
return x if x < y else remainder(x - y, y)Both give remainder(17, 7) == 3. They are previews of python-while-loops and python-recursion.