PythonPython Operators and ExpressionsPython operator precedence
What is operator precedence?
Question 47 of 88 · Updated
On this page
- 1. Precedence, associativity and evaluation order
- 2. Python operator precedence table
- 3. How an expression is grouped
- 4. Associativity and the special behavior of exponentiation
- 5. Arithmetic and bitwise operators in one expression
- 6. Comparisons and Boolean operators
- 7. Comparisons can chain
- 8. Grouping is not the same as evaluation order
- 9. Short-circuit evaluation can skip work
- 10. Conditional expressions and assignment expressions
- 11. Inspecting expression grouping using ast
- 12. Practical example: permission masks
- 13. Practical example: totals and named intermediate values
- 14. Common mistakes and failure cases
- Frequently asked questions
- Does Python follow the same order as mathematical arithmetic?
- Which has higher precedence, and or or?
- Are parentheses evaluated first?
- What is the difference between precedence and associativity?
- Does Python evaluate an expression from right to left when it contains ?
- Interview-ready answer
- Official references
Operator precedence determines how Python groups operators and operands when an expression contains multiple operations without explicit parentheses. An operator with higher precedence binds more tightly to its operands than an operator with lower precedence.
For example, in 8 + 4 * 3, multiplication binds more tightly than addition. Python interprets the expression as 8 + (4 * 3), producing 20 rather than 36.
Precedence is a rule about expression structure. It is related to, but distinct from, associativity and runtime evaluation order. Understanding all three prevents subtle bugs in arithmetic, Boolean conditions, bit masks and expressions that call functions.
1. Precedence, associativity and evaluation order#
| Concept | Question it answers |
|---|---|
| Precedence | Which operator binds more tightly? |
| Associativity | How do operators at the same precedence level group? |
| Evaluation order | When are operand expressions actually evaluated? |
| Short-circuit behavior | Which operand expressions might not be evaluated at all? |
PYTHONprint(8 + 4 * 3, (8 + 4) * 3, 20 - 6 - 2)
Output:
20 36 12The first two results demonstrate precedence and explicit grouping. The final expression demonstrates left grouping for subtraction: (20 - 6) - 2 is 12, whereas 20 - (6 - 2) would be 16.
Parentheses make the intended expression structure explicit. They do not, by themselves, require every parenthesized expression to be evaluated before unrelated operands elsewhere in the expression.
2. Python operator precedence table#
The following table presents common Python 3 expression constructs from highest binding strength to lowest. Constructs sharing a row have the same precedence in the corresponding grammar context.
| Precedence | Operators or expressions | Description |
|---|---|---|
| Highest | Parenthesized expressions and displays: (), [], {} | Explicit grouping, tuple/list/dict/set displays |
| 2 | Attribute access, subscription, slicing and calls | obj.attr, obj[index], obj[start:stop], f(...) |
| 3 | await expression | Awaiting an awaitable |
| 4 | ** | Exponentiation |
| 5 | Unary +, -, ~ | Unary positive, negative and bitwise inversion |
| 6 | *, @, /, //, % | Multiplicative operations |
| 7 | +, - | Addition and subtraction |
| 8 | <<, >> | Bit shifts |
| 9 | & | Bitwise AND |
| 10 | ^ | Bitwise XOR |
| 11 | `\ | |
| 12 | in, not in, is, is not, <, <=, >, >=, !=, == | Comparisons, membership and identity |
| 13 | not | Boolean negation |
| 14 | and | Boolean conjunction |
| 15 | or | Boolean disjunction |
| 16 | x if condition else y | Conditional expression |
| 17 | lambda | Lambda expression |
| Lowest | := | Assignment expression |
This is a practical version of the language reference's precedence table, not a substitute for the full expression grammar. Parentheses and displays are syntactic constructs, not ordinary binary operators. Await and assignment expressions have context-specific restrictions. The comma has distinct grammar roles in expression lists, argument lists and assignment targets; it is not an ordinary binary operator in this table.
Ordinary assignment with = and augmented assignment with +=, for example, are statements rather than expression operators. They are therefore not listed as competing precedence levels.
3. How an expression is grouped#
Consider 8 + 4 * 3. The expression tree below shows addition at the root, with multiplication forming the right operand of addition.
The trees describe two different expression structures: 8 + (4 * 3) and (8 + 4) * 3.
To reason about an arithmetic expression, identify its grouped subexpressions, calculate their results according to the operand types and combine those results using the surrounding operators. When functions or other side effects are present, also account for the language's operand evaluation order.
4. Associativity and the special behavior of exponentiation#
Most binary operators at the same precedence level group from left to right. Exponentiation is a notable exception: it groups from right to left. Conditional expressions also group from right to left. Comparisons have a special chaining rule rather than ordinary left-associated binary grouping.
PYTHONprint(2 ** 3 ** 2, (2 ** 3) ** 2) print(-2 ** 2, (-2) ** 2, 2 ** -2)
Output:
512 64
-4 4 0.25The expression 2 3 2 groups as 2 (3 2), giving 512. In contrast, (2 3) 2 explicitly produces 64.
Exponentiation interacts asymmetrically with unary signs. A unary minus on its left has lower binding strength, so -2 2 means -(2 2). A unary expression on its right is allowed as the exponent, so 2 -2 means 2 (-2).
The right-hand power subtree is the exponent of the outer power. Associativity specifies grouping, not necessarily the order in which operand expressions with side effects are called.
Do not confuse grammatical associativity with mathematical associativity. Floating-point addition can produce different results under different groupings because intermediate results may round, even though mathematical addition over exact real numbers is associative.
5. Arithmetic and bitwise operators in one expression#
PYTHONprint(1 << 2 + 1, (1 << 2) + 1) print(6 & 3 ^ 1 | 8)
Output:
8 5
11Addition binds more tightly than shifting, so 1 << 2 + 1 means 1 << (2 + 1), yielding 8. Explicitly shifting first gives 4 + 1, or 5.
In the second expression, bitwise AND binds more tightly than XOR, which binds more tightly than OR:
- 6 & 3 gives 2.
- 2 ^ 1 gives 3.
- 3 OR 8 gives 11.
The grouped expression is ((6 & 3) ^ 1) OR 8, where OR denotes the bitwise vertical-bar operator.
For bit-mask code, descriptive intermediate names or explicit parentheses can be more readable than relying on the reader to remember the entire precedence table.
6. Comparisons and Boolean operators#
Comparison operators bind more tightly than Boolean not. The not operator binds more tightly than and, and and binds more tightly than or.
PYTHONprint(not 3 < 5, True or False and False) print((True or False) and False)
Output:
False True
FalseThe expression not 3 < 5 groups as not (3 < 5), so the result is False.
True or False and False groups as True or (False and False). The left operand of or is already true, so the right-hand conjunction does not need to be evaluated.
With parentheses, (True or False) and False groups differently and produces False.
When combining policy conditions, use parentheses to make domain intent visible even if the default precedence would already give the intended result. This is particularly useful when mixing and and or.
7. Comparisons can chain#
Comparisons, membership tests and identity comparisons share a precedence level and participate in Python's comparison chaining syntax. A comparison chain is not interpreted as a sequence of Boolean-to-value comparisons.
PYTHONprint(1 < 2 < 3, (1 < 2) < 3) print(3 < 2 < 1, (3 < 2) < 1)
Output:
True True
False TrueThe chain 3 < 2 < 1 is false because its first adjacent comparison fails.
The parenthesized expression (3 < 2) < 1 instead compares False with 1. Since bool is a subclass of int and False has numeric value zero, this second expression evaluates to True.
For ordinary scalar values, a < b < c checks a < b and b < c, evaluating b only once if reached and skipping later operands when an earlier comparison fails. Custom comparison results may require truth testing and may not themselves be Boolean objects.
The earlier comparison-operators lesson explores chaining and rich comparison behavior in more detail.
8. Grouping is not the same as evaluation order#
Python generally evaluates ordinary operand expressions from left to right. Higher-precedence operators determine how the resulting operands are combined, rather than requiring every expression on the right to run before any expression on the left.
PYTHONdef mark(x): print(x) return x print(mark(2) + mark(3) * mark(4))
Output:
2
3
4
14The leftmost function runs first, printing 2. The remaining function calls print 3 and 4. The multiplication operation combines the latter two values, and addition combines 2 with their product.
This is why a statement such as "multiplication always executes before addition" can be misleading when discussing expressions that have side effects. Multiplication binds more tightly in the expression tree, but the operand calls follow the evaluation rules of the language.
Keep side effects out of complicated arithmetic and comparison expressions when practical. Breaking the logic into intermediate assignments makes evaluation order easier to inspect and test.
9. Short-circuit evaluation can skip work#
PYTHONdef fail(): raise RuntimeError("not needed") print(False and fail(), True or fail()) print(3 < 2 < fail())
Output:
False True
FalseThe fail function is never invoked in these three expressions. The logical operations can determine their results from the left operand, and the comparison chain stops after its first false comparison.
A high-precedence expression is not guaranteed to execute merely because it binds tightly. Short-circuiting determines whether evaluation reaches that part of the expression at all.
The and and or operators return one of their evaluated operands. They do not necessarily return a bool, unlike not, which returns a Boolean value. This distinction was introduced in the Boolean lesson.
10. Conditional expressions and assignment expressions#
Conditional expressions select one of two expressions based on a condition and have relatively low precedence.
PYTHONprint(2 + 3 if False else 4 * 5) print("A" if False else "B" if True else "C")
Output:
20
BThe first conditional expression groups as (2 + 3) if False else (4 * 5). Only the selected branch is evaluated after the condition.
The second expression groups as "A" if False else ("B" if True else "C"). Nested conditional expressions can be difficult to read even when their grouping is correct. Prefer an ordinary if/elif/else statement if the conditions are complicated.
The assignment expression := has low precedence and binds a name while producing its value. In a condition such as if (size := len("abc")) >= 3, the parentheses specify that the length, rather than a comparison result, is assigned to size. Assignment expressions also have grammar restrictions that precedence alone cannot explain.
11. Inspecting expression grouping using ast#
The standard-library ast module allows a developer to inspect how Python parsed an expression without executing that expression.
PYTHONimport ast node=ast.parse("a + b * c",mode="eval").body print(type(node.op).__name__,type(node.right.op).__name__)
Output:
Add MultThe outer node is a binary addition operation, and its right child is a multiplication operation. This matches the expression's precedence rules.
AST inspection can be useful for learning grammar, developing static analysis tools or debugging code transformations. It is not necessary for ordinary arithmetic, but provides an independently inspectable representation of grouping.
Parsing is not the same as evaluating. Do not use eval on untrusted input to experiment with expression precedence. If an application accepts a user-defined mathematical expression, implement an appropriate restricted grammar and enforce input and resource limits.
12. Practical example: permission masks#
PYTHONflags=5; required=3 print((flags & required) == required, bool(flags & required)) print(1 & 2 == 0, 1 & (2 == 0))
Output:
False True
True 0The flags value 5 has binary representation 101. The required mask 3 has binary representation 011. The AND result is 1, which is not the complete required mask, although it is truthy.
In the second line, bitwise AND binds more tightly than equality. Thus 1 & 2 == 0 means (1 & 2) == 0, producing True. Explicitly grouping 2 == 0 produces False as the right operand of &, and the resulting integer bitwise operation gives 0.
The example shows how parentheses can change both the value and the result type. Use an explicit all-bits comparison or any-bits truth test according to the intended flag policy. Real access-control decisions must be enforced at a trusted boundary and use authoritative permission information.
13. Practical example: totals and named intermediate values#
PYTHONdef total(qty, unit, discount, fee): return qty * unit - discount + fee print(total(3, 200, 50, 20)) if (size := len("abc")) >= 3: print(size)
Output:
570
3Multiplication computes the initial subtotal of 600. Subtraction and addition then group from the left, producing 550 and finally 570.
The function assumes appropriate numeric inputs and a defined unit. A financial calculation should validate quantities and define currency units and rounding policies. Separating subtotal, discount and final total into named intermediate values may improve readability when rules grow more complex.
There are a bounded number of arithmetic operations in this example. Under fixed-size integer cost assumptions, time and auxiliary space are O(1). Actual operation costs for arbitrary-precision integers and custom numerical types can depend on the operand sizes and implementations.
14. Common mistakes and failure cases#
| Mistake | Correction |
|---|---|
| Treating exponentiation as left-associated | Remember that a b c groups from the right |
| Assuming -x ** 2 squares a negative base | Use (-x) ** 2 when the negative value is the intended base |
| Confusing precedence with function-call order | Track operand evaluation separately |
| Treating a comparison chain as nested binary comparisons | Understand the special adjacent-comparison rule |
| Mixing logical and bitwise syntax | Use the operator family matching the intended operation |
| Relying on precedence to avoid invalid arithmetic | Guard invalid operations explicitly when needed |
Precedence rules do not make an invalid operation valid. Three independent failure tests confirm that 1/0 raises ZeroDivisionError, an ordinary assignment in an if condition raises SyntaxError, and 1 << -1 raises ValueError.
Frequently asked questions#
Does Python follow the same order as mathematical arithmetic?#
For many common arithmetic expressions, yes: exponentiation, multiplicative operations and additive operations have their usual relative binding strengths. Python also defines additional operators, comparison chaining and special unary-power rules that are not fully explained by a simple arithmetic mnemonic.
Which has higher precedence, and or or?#
The and operator binds more tightly than or. Use parentheses when a different grouping is required or when the intended grouping is not obvious.
Are parentheses evaluated first?#
Parentheses establish expression grouping. Actual operand evaluation follows Python's execution rules. An expression inside parentheses can still be skipped by a short-circuit operation or an unselected conditional branch.
What is the difference between precedence and associativity?#
Precedence resolves grouping across different operator levels. Associativity resolves ordinary grouping within the same level, with exceptions such as comparison chains.
Does Python evaluate an expression from right to left when it contains **?#
Exponentiation groups from the right, but ordinary operand expressions still follow the language's evaluation-order rules. Grouping and evaluation order are separate concepts.
Interview-ready answer#
Operator precedence in Python determines how expressions containing multiple operators are grouped. For example, multiplication binds more tightly than addition, so 8 + 4 * 3 evaluates to 20. Associativity determines ordinary grouping among operators at the same precedence level: subtraction groups left to right, while exponentiation groups right to left. Comparisons have a special chaining rule. Parentheses override default grouping, and precedence must not be confused with runtime evaluation order or short-circuit behavior. Understanding these distinctions helps write readable expressions and avoid subtle arithmetic, comparison and Boolean errors.
Official references#
- Python Language Reference — Operator precedence
- Python Language Reference — Evaluation order
- Python Language Reference — The power operator
- Python Language Reference — Comparisons
- Python Language Reference — Boolean operations
- Python Standard Library — ast
- PEP 572 — Assignment Expressions
Verification note: All eleven runnable example groups were executed in isolated namespaces on CPython 3.13.5 and matched their documented outputs. Three independent expected-exception tests passed. Three fenced Mermaid diagrams were manually reviewed for grouping and evaluation semantics. The local Mermaid package and CLI were unavailable, so parser-level validation and public-site rendering remain unverified. Official reference links are provided under the authorized offline research exception; live documentation and the Supabase changelog were not checked.
References
- 1.Python Language Reference — Operator precedencedocs.python.org
- 2.Python Standard Library — astdocs.python.org
- 3.PEP 572 — Assignment Expressionspeps.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design