Python Operator Precedence
Rules, Examples, and Evaluation Order

Operator Precedence

When Python evaluates an expression, the order in which operations occur can drastically affect the result. This is known as operator precedence. Just like in regular arithmetic, multiplication comes before addition—Python uses similar rules internally.

Why Operator Precedence Matters

Imagine the expression 3 + 4 * 2. Should Python add 3 and 4 first, or multiply 4 and 2? Without knowing the precedence rules, you'd be guessing.

Python follows a strict hierarchy of operators. Misunderstanding this hierarchy can lead to incorrect results, confusing bugs, or unexpected behavior.

Python Operator Precedence Table

Here’s the standard operator precedence in Python, from highest to lowest:

PrecedenceOperatorsDescription
1()Parentheses
2**Exponentiation
3+x, -x, ~xUnary plus, minus, bitwise NOT
4*, /, //, %Multiplication, division, floor division, modulus
5+, -Addition, subtraction
6<<, >>Bitwise shift
7&Bitwise AND
8^Bitwise XOR
9|Bitwise OR
10==, !=, >, <, >=, <=Comparisons
11notLogical NOT
12andLogical AND
13orLogical OR
14=, +=, -=, *=, /= ...Assignment operators

How Python Evaluates Expressions

Let’s see Python in action. Try predicting the output before running the code:

result = 10 + 5 * 2
print("Result:", result)
Result: 20

Explanation

Multiplication (*) has higher precedence than addition (+), so 5 * 2 is evaluated first, giving 10. Then 10 + 10 results in 20.

Using Parentheses to Control Evaluation

When in doubt, use parentheses to make the order explicit and readable:

result = (10 + 5) * 2
print("Result:", result)
Result: 30

Explanation

This time, 10 + 5 is evaluated first due to the parentheses, resulting in 15, which is then multiplied by 2.

Examples

Example 1: Logical vs Arithmetic

value = 3 + 2 > 4 and not False
print("Value:", value)
Value: True

Explanation

  • 3 + 2 → 5
  • 5 > 4 → True
  • not False → True
  • True and True → True

Example 2: Division and Exponentiation

result = 100 / 10 ** 2
print("Result:", result)
Result: 1.0

Explanation

10 ** 2 is evaluated first, giving 100. Then 100 / 100 gives 1.0.

Operator Associativity

When two operators have the same precedence, Python uses associativity to decide the order. Most operators are left-associative (evaluated left to right), except **, which is right-associative.

result = 2 ** 3 ** 2
print("Result:", result)
Result: 512

This is equivalent to 2 ** (3 ** 2)2 ** 9 → 512.

Things to Keep in Mind

  • Always use parentheses if the expression feels ambiguous.
  • For readability and debugging, simplify complex expressions step by step.
  • Be especially cautious when mixing comparison, logical, and arithmetic operators.