Precedence and Associativity of Operators in Python
1. What is Operator Precedence
Operator precedence determines the order in which operators are evaluated in an expression.
result = 10 + 5 * 2
print(result) # 20, not 30Multiplication (*) has higher precedence than addition (+).
2. What is Operator Associativity
Associativity determines the direction of evaluation when operators have the same precedence.
result = 100 / 10 / 2
print(result) # 5.0Division is left-to-right associative: (100 / 10) / 2
3. Using Parentheses to Override Precedence
result = (10 + 5) * 2
print(result) # 30Parentheses explicitly control evaluation order.
4. Arithmetic Operator Precedence
result = 2 + 3 * 4 - 5
print(result) # 9Evaluation order:
*+-
5. Comparison and Logical Precedence
Order:
Comparison (
>)Logical AND (
and)
6. Logical Operator Hierarchy
Order:
notandor
So this becomes: True or (False and False)
7. Assignment Precedence
Assignment (=) has lower precedence than arithmetic operators.
8. Exponentiation Associativity (Right to Left)
Evaluated as: 2 ** (3 ** 2) = 2 ** 9
9. Bitwise Operator Precedence
Order:
&|
Bitwise operations follow strict precedence for predictable results.
10. Complex Expression Evaluation Example
Step-by-step:
Exponentiation →
2 ** 3 = 8Multiplication →
8 * 4 = 32Addition →
5 + 32 = 37Comparison →
37 > 20→ TrueLogical NOT → not False → True
AND → True and True → True
Operator Precedence Table (High → Low)
Highest
()
**
+x, -x, ~x
*, /, //, %
+, -
<<, >>
&
^
`
Comparisons (==, !=, >, <, >=, <=)
not
and
Lowest
or
Associativity Summary
Most operators
Left → Right
Exponentiation (**)
Right → Left
Assignment (=)
Right → Left
Best Practices
Use parentheses for readability and predictability
Avoid overly complex expressions
Break expressions into multiple lines if logic becomes unclear
Never rely on memory for precedence in critical logic
Enterprise Relevance
Understanding precedence ensures:
Accurate business rule logic
Correct financial calculations
Reliable conditional flows
Bug-free algorithm design
This is critical in:
Quant systems
Validation engines
Rule-based AI logic
Workflow automations
Last updated