➕ Operators & Expressions
Module 3 · Topic 7

Operator Precedence & Associativity

Understand the order in which Python evaluates operators to avoid bugs and write clear expressions.

Theory

Operator Precedence (Highest to Lowest):

| Priority | Operator | Description |
|----------|----------|-------------|
| 1 | () | Parentheses |
| 2 | ** | Exponentiation |
| 3 | ~, +x, -x | Unary NOT, positive, negative |
| 4 | *, /, //, % | Multiplication, division, modulus |
| 5 | +, - | Addition, subtraction |
| 6 | <<, >> | Bitwise shifts |
| 7 | & | Bitwise AND |
| 8 | ^ | Bitwise XOR |
| 9 | | | Bitwise OR |
| 10 | ==, !=, <, >, <=, >=, is, in | Comparisons |
| 11 | not | Logical NOT |
| 12 | and | Logical AND |
| 13 | or | Logical OR |
| 14 | := | Walrus operator |

Associativity:

  • Most operators: left-to-right (5 - 3 - 1 = 1)
  • Exponentiation : right-to-left (23**2 = 512)
  • Assignment =: right-to-left (a = b = 5)

Best Practice: When in doubt, use parentheses for clarity!

Syntax
# Precedence example
result = 2 + 3 * 4    # 14, not 20
result = (2 + 3) * 4  # 20 — parentheses override

# Associativity
result = 2 ** 3 ** 2  # 512 (right-to-left)
result = 10 - 5 - 2   # 3 (left-to-right)