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 30

Multiplication (*) 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.0

Division is left-to-right associative: (100 / 10) / 2


3. Using Parentheses to Override Precedence

result = (10 + 5) * 2
print(result)  # 30

Parentheses explicitly control evaluation order.


4. Arithmetic Operator Precedence

result = 2 + 3 * 4 - 5
print(result)  # 9

Evaluation order:

  1. *

  2. +

  3. -


5. Comparison and Logical Precedence

Order:

  1. Comparison (>)

  2. Logical AND (and)


6. Logical Operator Hierarchy

Order:

  1. not

  2. and

  3. or

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:

  1. &

  2. |

Bitwise operations follow strict precedence for predictable results.


10. Complex Expression Evaluation Example

Step-by-step:

  1. Exponentiation → 2 ** 3 = 8

  2. Multiplication → 8 * 4 = 32

  3. Addition → 5 + 32 = 37

  4. Comparison → 37 > 20 → True

  5. Logical NOT → not False → True

  6. AND → True and True → True


Operator Precedence Table (High → Low)

Precedence
Operator

Highest

()

**

+x, -x, ~x

*, /, //, %

+, -

<<, >>

&

^

`

Comparisons (==, !=, >, <, >=, <=)

not

and

Lowest

or


Associativity Summary

Operator Type
Associativity

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