Sub topic 17
Operator Precedence and Associativity
This chapter assumes you know the arithmetic, comparison, logical, and bitwise operators from the earlier chapters. It covers how Python decides which operator applies first when an expression has several. You will be able to predict the grouping of any expression and know when to add parentheses.
Two rules decide the grouping
Python's parser applies two rules to every expression.
- Precedence ranks operators. In
2 + 3 * 4,*ranks higher than+, so it groups first and the result is14. - Associativity breaks ties between operators of the same rank. In
10 - 4 - 3, both operators are-. Most operators group left to right, so this means(10 - 4) - 3, which is3.
Grouping is a parsing decision. It does not change the order in which operands are evaluated, which is covered later in this chapter.
The precedence table
The table runs from the tightest binding (top) to the loosest (bottom). Operators in the same row have equal rank.
| Rank | Operators | Associativity | Column |
|---|---|---|---|
| 1 | `(...)`, `[...]`, `{...}` | n/a | |
| 2 | `x[i]`, `x.attr`, `f(x)` | left to right | |
| 3 | `**` | right to left | |
| 4 | `+x`, `-x`, `~x` | right to left | |
| 5 | `*`, `/`, `//`, `%`, `@` | left to right | |
| 6 | `+`, `-` | left to right | |
| 7 | `<<`, `>>` | left to right | |
| 8 | `&` | left to right | |
| 9 | `^` | left to right | |
| 10 | `\ | ` | left to right |
| 11 | `in`, `not in`, `is`, `is not`, `<`, `<=`, `>`, `>=`, `!=`, `==` | chained | |
| 12 | `not x` | right to left | |
| 13 | `and` | left to right | |
| 14 | `or` | left to right | |
| 15 | `x if c else y` | right to left | |
| 16 | `lambda` | n/a | |
| 17 | `:=` | n/a |
Two features of this table cause most mistakes. Bitwise operators rank above comparisons, which is the opposite of C. The logical operators rank below comparisons, and and ranks above or.
Seeing the grouping
You can ask Python for its parse tree and print every grouping explicitly. This helper handles the operators used in this section.
import ast
OPS = {
ast.Add: "+",
ast.Sub: "-",
ast.Mult: "*",
ast.Div: "/",
ast.Pow: "**",
ast.USub: "-",
}
def group(node):
if isinstance(node, ast.BinOp):
return f"({group(node.left)} {OPS[type(node.op)]} {group(node.right)})"
if isinstance(node, ast.UnaryOp):
return f"({OPS[type(node.op)]}{group(node.operand)})"
if isinstance(node, ast.Constant):
return repr(node.value)
raise ValueError(f"unsupported node: {type(node).__name__}")
for source in ["1 + 2 * 3 ** 2 - 4", "-2 ** 2", "2 ** 3 ** 2",
"10 - 4 - 3", "8 / 2 * 4", "2 ** -1"]:
print(f"{source:20} -> {group(ast.parse(source, mode='eval').body)}")The output is:
1 + 2 * 3 ** 2 - 4 -> ((1 + (2 * (3 ** 2))) - 4)
-2 ** 2 -> (-(2 ** 2))
2 ** 3 ** 2 -> (2 ** (3 ** 2))
10 - 4 - 3 -> ((10 - 4) - 3)
8 / 2 * 4 -> ((8 / 2) * 4)
2 ** -1 -> (2 ** (-1))The first expression forms this tree. Operators lower in the tree run first.
Left and right associativity
Binary operators group left to right, so 8 / 2 * 4 is (8 / 2) * 4, which is 16.0. Writing 8 / (2 * 4) gives 1.0, a different value.
** is the main exception. It groups right to left, which matches mathematical convention:
print(2 ** 3 ** 2) # 2 ** 9
print((2 ** 3) ** 2) # 8 ** 2This prints 512 and then 64.
Assignment also groups right to left. In a = b = [], the empty list is evaluated once and bound to both names, so a and b refer to the same list.
Conditional expressions group right to left too, so they can be chained without parentheses:
def grade(score):
return "A" if score >= 90 else "B" if score >= 80 else "C"
print(grade(95), grade(85), grade(50))This prints A B C. The second if belongs to the else branch of the first.
Unary minus and `**`
The ** operator binds tighter than a unary operator on its left, so -2 ** 2 is -(2 ** 2), which is -4. On its right side, ** accepts a unary operator, so 2 ** -1 is 0.5 and does not raise a syntax error. If you want a negative base, write (-2) ** 2.
Comparisons chain instead of nesting
All comparison operators share one rank, and they do not group left to right. A run of them forms a chain, as in 1 < x < 10. The expression 1 < 2 == 2 means 1 < 2 and 2 == 2, which is True. This also applies to is and in, so a chain like a == b is c can surprise you. Do not mix operator kinds in a single chain.
Common precedence traps
These expressions behave differently from what many readers expect.
print(6 & 3 == 2) # & binds tighter than ==
print(1 + 2 << 3) # + binds tighter than <<
print(not 1 == 2) # not applies after ==
print(True or False and False)
print(-7 // 2 * 2)The output is True, 24, True, True, and -8.
6 & 3 == 2is(6 & 3) == 2. In C, the same text would compare3 == 2first.1 + 2 << 3is(1 + 2) << 3, so shifts rank below addition.True or False and FalseisTrue or (False and False), becauseandranks aboveor.-7 // 2 * 2is((-7) // 2) * 2, which is-4 * 2.
Another trap is mixing or with a conditional expression. a or b if c else d means (a or b) if c else d, because the conditional expression ranks below or.
Evaluation order is separate from precedence
Precedence decides the tree. Python still evaluates operands from left to right, and a higher-ranked operator does not make its operands run earlier. This function makes the order visible:
def show(n):
print("eval", n)
return n
print(show(1) + show(2) * show(3))
print(show(2) ** show(3) ** show(2))The first expression prints eval 1, eval 2, eval 3, then 7. The multiplication runs before the addition, but show(1) is still called first. The second expression prints eval 2, eval 3, eval 2, then 512. Operands are evaluated left to right even though ** groups right to left. Short-circuit operators such as and, or, and the conditional expression are the exception, because they skip operands they do not need.
The loosest operators
lambda and := rank lowest, which has practical effects.
- A lambda body extends as far to the right as possible.
lambda x: x + 1 if x else 0is a single function whose body is the whole conditional expression. - The walrus operator needs parentheses in most contexts. Write
y = (x := 5) + 1. Without the parentheses,x := 5cannot be used as an operand of+.
Choosing parentheses
Exercise
What does print(2 ** 3 ** 2 - -1) print, and how does Python group it?
Show answer
It prints 513. Python groups it as (2 (3 2)) - (-1). The inner 3 2 is 9, then 2 9 is 512, and subtracting -1 gives 513. The unary minus on the right is allowed because the operator on its left is -, and it applies to 1 alone.
Exercise
What does print(not 0 or 1 and 0) print, and which part is evaluated first?
Show answer
It prints True. The not ranks above and, which ranks above or, so the grouping is (not 0) or (1 and 0). The left side is True, so or returns True, and the and part never needs to run.