Python - Operator Precedence

Overview

Estimated time: 20–30 minutes

Operator precedence determines which operations are evaluated first in an expression. Understanding this avoids subtle bugs and improves code readability.

Learning Objectives

  • Know Python’s operator precedence and associativity rules.
  • Predict evaluation of complex expressions and parenthesize intentionally.
  • Recognize short-circuit behavior for boolean operators.

Prerequisites

  • Basic familiarity with Python operators and expressions

Quick Reference (highest → lowest)

Common subset: parentheses () → exponentiation ** (right-assoc) → unary + - ~ → multiply/divide * / // % → add/subtract + - → shifts << >> → bitwise & then ^ then | → comparisons < <= > >= == != is in → not → and → or → if-else expression → assignment (walrus :=)

Examples

print(2 + 3 * 4)          # 14, * before +
print((2 + 3) * 4)        # 20
print(2 ** 3 ** 2)        # 512, right-associative: 2 ** (3 ** 2)
print(-3 ** 2)            # -9, unary - after **; use (-3) ** 2 for 9
print(1 or 0 and 5)       # 1, and before or; also short-circuiting

# Short-circuiting returns operands, not coerced booleans
x = []
print(x or [42])          # [42]
print(x and [42])         # []

Expected Output:

14
20
512
-9
1
[42]
[]

Common Pitfalls

  • Unary minus vs exponentiation: -3 ** 2 is -(3 ** 2), not (-3) ** 2.
  • Chained comparisons: a < b < c is equivalent to a < b and b < c and evaluates b once.
  • Boolean short-circuit values: and/or return operands, not True/False.
  • Readability: when in doubt, add parentheses.

Best Practices

  • Use parentheses generously to document intent.
  • Avoid overly clever one-liners; split into intermediate variables.
  • Prefer explicit if/else over nested ternaries for clarity.

Checks for Understanding

  1. What is the value of 2 + 3 * 2 ** 2?
  2. How does a or b choose which value to return?
Show answers
  1. 2 + 3 * (2 ** 2) = 2 + 3 * 4 = 14.
  2. It returns a if a is truthy; otherwise returns b.

Exercises

  1. Rewrite a complex expression with parentheses to make evaluation order obvious.
  2. Create examples showing the difference between -3 ** 2 and (-3) ** 2.