Sub topic 17
Operator precedence and associativity
This chapter assumes you can run Python code and already know the operators from the earlier chapters: arithmetic, comparison, logical, bitwise and assignment. Here you learn how Python groups an expression that mixes several of them.
Precedence decides which operator goes first
Precedence ranks operators. Python evaluates higher-ranked operators before lower-ranked ones, and the operands of each operator are grouped before the next rank is considered.
The table lists the groups you use most, from tightest to loosest binding.
| Rank | Operators | Column |
|---|---|---|
| 1 | `( )` parentheses | |
| 2 | `**` | |
| 3 | unary `+x`, `-x`, `~x` | |
| 4 | `*`, `/`, `//`, `%` | |
| 5 | `+`, `-` | |
| 6 | `<<`, `>>` | |
| 7 | `&`, then `^`, then ` | ` |
| 8 | `==`, `!=`, `<`, `>`, `<=`, `>=`, `is`, `in` | |
| 9 | `not` | |
| 10 | `and`, then `or` | |
| 11 | `x if c else y` | |
| 12 | `:=` |
Associativity breaks ties
When two operators have the same rank, associativity decides the grouping. Most binary operators are left-associative, so they group from the left. The ** operator is right-associative. Comparisons are a special case, because they chain as described in the earlier chapter.
print(2 + 3 * 4 ** 2)
print(10 - 3 - 2)
print(100 / 10 / 5)
print(2 ** 3 ** 2)
print((2 ** 3) ** 2)This prints 50, 5, 2.0, 512 and 64. The line 10 - 3 - 2 is (10 - 3) - 2. The line 2 ** 3 ** 2 is 2 ** (3 ** 2).
Gotchas
The unary minus ranks below ** on its left but above it on its right. So -2 ** 2 is -(2 ** 2), which is -4, while 2 ** -1 is 0.5.
Bitwise operators rank above comparisons in Python, which differs from C. This makes x & 1 == 0 mean (x & 1) == 0. Shifts rank below addition, so 1 << 2 + 1 is 1 << 3.
x = 6
print(-2 ** 2)
print(2 ** -1)
print(x & 1 == 0)
print(1 << 2 + 1)
print(True or False and False)
print((True or False) and False)This prints -4, 0.5, True, 8, True and False. Because and ranks above or, the fifth line is True or (False and False).
Assignment is not an expression operator
Plain = is a statement, not part of this table. a = b = 0 assigns 0 to both names, working from left to right through the targets. The walrus operator := is an expression, and it ranks lowest, so you usually need to parenthesize it: if (n := len(data)) > 2.
Exercise
What does 2 * 3 ** 2 % 5 evaluate to, and how is it grouped?
Show answer
It evaluates to 3. The ** operator goes first, giving 3 ** 2 = 9. The operators * and % have the same rank and are left-associative, so the grouping is (2 * 9) % 5. That is 18 % 5, which is 3.