Order of Precedence in Python Explained (With Real Examples) ⚙️

If you’ve ever written a Python expression and ended up scratching your head at the output, you're not alone.

Python, like many languages, follows strict rules when evaluating expressions involving multiple operators.

Order of Precedence in Python Explained (With Real Examples) ⚙️

These rules are known as operator precedence (which operations happen first) and operator associativity (what happens if operators share the same priority). Understanding both helps you avoid bugs, write clearer code, and debug faster.

In this article-you’ll learn:

1. What operator precedence and associativity actually mean

2. A comprehensive breakdown of Python's operator hierarchy

3. Real examples showing how Python evaluates complex expressions

4. Why these rules matter in everyday coding

5. How to use parentheses effectively when in doubt

🤔 What Is Operator Precedence?\

Operator precedence determines which part of an expression Python evaluates first. When faced with multiple operators, Python checks whose precedence is highest and evaluates that operation before moving on. For example:

Copy Code

result = 3 + 4 * 5

Even though + appears first in reading order, * (multiplication) has higher precedence, so Python calculates:

Copy Code

4 * 5 = 20

3 + 20 = 23

🔀 What Is Operator Associativity?

Associativity comes into play when operators of equal precedence are in sequence. It determines which order they’re evaluated,left-to-right or right-to-left. Most operators are left-to-right associative, but a few like exponentiation (**) and assignment (=) are right-to-left.

For example:

Copy Code

expression = 100 / 10 * 2

Multiplication and division share precedence, so Python evaluates them from left to right:

Copy Code

100 / 10 = 10

10 * 2 = 20

📋 Full Python Operator Precedence Table

Here’s a clearer, ordered list-from highest to lowest precedence-based on common tutorials (WsCubeTech, GeeksforGeeks, Programiz, and others). I've included associativity and a hint of usage:

 

Precedence LevelOperators Description Associativity 
1()Parentheses (grouping)-
2[], ., () (function call)Indexing, attribute reference, function callLeft to Right
3**ExponentiationRight to Left 
4x, -x, ~xUnary plus, minus, bitwise NOTRight to Left
5*, /, //, %Multiplication, division, floor, moduloLeft to Right
6+, -Addition, subtractionLeft to Right
7<, >>Bitwise shiftsLeft to Right
8&Bitwise ANDLeft to Right
9^Bitwise XORLeft to Right
10``Bitwise OR
11=, !=, <, >, <=, >=, is, in, not in, is notComparisonsLeft to Right
12NotLogical NOTRight to Left
13AndLogical ANDLeft to Right
14OrLogical ORRight to Left
15If…elseConditional expressionRight to Left
16=, +=, -=,etcAssignment operatorsRight to Left
17LambaLambda functionRight to Left

(Abilities combined from WsCubeTech, GeeksforGeeks, Tpoint Tech, Programiz, and LogicalPython) 

📌 Examples That Clarify Precedence and Associativity

1. Exponentiation Goes Right to Left

Copy Code

x = 2 ** 3 ** 2

# Evaluated as 2 ** (3 ** 2) = 2 ** 9 = 512

If you mistakenly did (2 ** 3) ** 2, you'd get 64-not what Python does. This right-to-left behavior is confirmed by WsCubeTech and others. 

2. Multiplication Before Addition

Copy Code

print(5 + 2 * 3)  # Output: 11

# Multiplication (2*3=6) resolves first; then 5+6 = 11

3. Parentheses Override Everything

Copy Code

print((5 + 2) * 3)  # Output: 21

Since parentheses are top priority, 5 + 2 = 7, then 7 * 3 = 21.

4. Logical Operators Precedence

Copy Code

a, b = True, False

print(a or b and True)

# 'and' runs before 'or': a or (b and True) = True

Even if b and True is False, the or operation with a=True makes the result True. WsCubeTech and Programiz both show this behavior. 

Without parentheses:

Copy Code

if name == "Alex" or name == "John" and age >= 2:

    ..

This is parsed as name=="Alex" or (name=="John" and age>=2), not (name=="Alex" or name=="John") and age>=2. WsCubeTech shows how parentheses shift the logic.  

5. Chained Comparison Operators

Copy Code

print(5 < 7 < 9)  # True

This doesn’t mean (5 < 7) < 9 or 5 < (7 < 9). Python treats it as (5 < 7) and (7 < 9) and evaluates left to right. Non-associative, yet built-in chaining-confirmed by Programiz and WsCubeTech.  

6. Chained Assignments (Right to Left)

Copy Code

a = b = c = 5

Python processes it as:

Copy Code

c = 5

b = 5

a = 5

This works perfectly. But something like a = b = c += 2 is invalid and causes a syntax error-because += can't be combined like that. This is documented by multiple sources.  

7. Floor Division and Modulo Together

Copy Code

print(4 * 9 // 3)       # Output: 12

print(4 * (9 // 3))     # Still 12, but parentheses highlight the order

The first runs multiplication and floor division left-to-right. Both evaluations yield the same result, but parentheses help clarify intent.  

🛑 Common Pitfalls and Gotchas

1. Assuming Left-to-Right Always Applies

Unlike human math conventions, Python doesn’t assume simple left-to-right. Operators with higher precedence can change the flow.

Copy Code

print(10 + 2 * 3)  # 16, not 36

2. Misunderstanding Exponent Order

Copy Code

2 ** 3 ** 2 is not (2**3) ** 2, it's 2 ** (3**2). Use parentheses if needed.

3. Logical Expressions Without Parentheses

Copy Code

if a or b and c:

    …

Without parentheses, b and c is evaluated first. This can cause unexpected logic. All official sources stress parentheses to avoid confusion.  

4. Chaining Assignments Incorrectly

Copy Code

x = y = z += 9

# ❌ SyntaxError

You’ll see errors when trying to combine chained assignment with augmented assignment. 

🧠 Why All This Matters

🔧 Prevent Bugs

Misjudging precedence leads to unexpected behavior-spend fewer hours debugging.

✍️ Write Cleaner Code

Proper parentheses make your logic explicit and aid future readers (even future you).

🔍 Improve Debugging Skills

When something doesn’t behave as expected, knowing precedence helps you narrow the issue faster.

✅ Handy Tips

1. When uncertain, add parentheses.

Extra clarity beats unintended bugs.

2. Break complex expressions into smaller bits.

Use intermediate variables to see intermediate values.

3. Bookmark a precedence table 

4. Practice frequently.

Make mental note of patterns like exponentiation binding tight or logical operators often needing parentheses.

🧑‍💻 Final Thoughts

Operator precedence and associativity are design choices that directly impact how your code runs. From your simplest arithmetic to complex Boolean checks and chained assignments, Python follows a strict-but learnable-set of rules. Once you internalize the precedence hierarchy and associativity patterns (left vs. right), you’ll not only write more accurate code-you’ll understand why it works that way.

Your key takeaway:

> Precedence tells you which operator runs first. Associativity tells you how operators of the same priority are grouped. Always add parentheses when clarity matters.

Understanding these concepts isn't just academic-it’s a step toward writing robust, professional-quality code. So next time you type a complex expression, take a moment to think: “Is this really how I want it to run?” If there’s any doubt, parentheses got your back.

🚀 Atlast

Precedence means which operation comes first (e.g., * over +).

Associativity decides how same-level operators are grouped (e.g., left-to-right vs. right-to-left).

Most operators are left-to-right—exceptions: **, not, assignments.

Use parentheses to clarify and override default behavior.

Common pitfalls include misunderstanding chaining, exponent order, and logical evaluation.

Clear, well-grouped expressions mean less bugs and better code maintainability.

Placed Students

Our Clients

Partners

...

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses