Python Mastery – From Basics to Brilliance / Operators in Python

Operator Precedence & Associativity

When Python sees an expression with multiple operators, it needs to decide:

  • Which operation to do first? → Precedence

  • In what direction to evaluate when precedence is the same? → Associativity


🔝 Operator Precedence

Precedence means which operator gets executed first when there are no parentheses.

💡 Example:

result = 2 + 3 * 4
# NOT (2 + 3) * 4 → would be 20
# BUT: 2 + (3 * 4) → 2 + 12 = 14

👉 Here, * (multiplication) has higher precedence than +, so it runs first.


🔁 Associativity

Associativity tells which direction to evaluate operators of the same precedence:

  • Left-to-right: Most operators like +, , /, //, %

  • Right-to-left: Assignment operators and exponentiation (=, +=, *)


🔢 Operator Precedence Table

(Top = Highest priority)

Priority

Operators

Type

Associativity

1️⃣

()

Parentheses

—

2️⃣

**

Exponentiation

Right to Left

3️⃣

+x, -x, ~x

Unary plus, minus, bitwise NOT

Right to Left

4️⃣

*, /, //, %

Multiplication, Division, Modulo

Left to Right

5️⃣

+, -

Addition, Subtraction

Left to Right

6️⃣

<, <=, >, >=, ==, !=

Comparisons

Left to Right

7️⃣

not

Logical NOT

Right to Left

8️⃣

and

Logical AND

Left to Right

9️⃣

or

Logical OR

Left to Right

✅ Tip: Always use parentheses () to make your expressions clear and bug-free.