Here is a clear, simple, and exam-oriented explanation of the Associativity of Operators in Python, perfect for BCA/MCA/B.Tech students.
Associativity of Operators in Python
Associativity defines the direction in which an expression with operators of same precedence level is evaluated.
When two or more operators have the same precedence, Python uses associativity rules to decide whether to evaluate an expression from:
- Left to Right (Left Associative)
or - Right to Left (Right Associative)
Why Associativity is Needed?
Consider this expression:
10 - 5 + 2
Operators - and + have the same precedence, so which one is evaluated first?
Because Python evaluates using left-to-right associativity, it becomes:
(10 - 5) + 2 = 7
Not:
10 - (5 + 2) = 3
Types of Associativity
Python uses two kinds:
- Left-to-Right Associativity
- Right-to-Left Associativity
1. Left-to-Right Associativity
Most operators in Python are left associative.
This means:
a op b op c → (a op b) op c
Operators with Left-to-Right associativity:
- Arithmetic Operators:
+ - * / % // - Relational (Comparison) Operators:
< > <= >= == != - Bitwise Operators:
& ^ | << >> - Logical Operators:
and or
Examples:
Example 1:
10 - 5 + 2
Left to right:
(10 - 5) + 2 = 7
Example 2:
20 / 5 * 2
Left to right:
(20 / 5) * 2 = 4 * 2 = 8
Example 3:
4 >> 1 << 1
Left to right:
(4 >> 1) << 1 = 2 << 1 = 4
2. Right-to-Left Associativity
Some operators evaluate right to left.
Operators with Right-to-Left associativity:
- Exponent Operator (
**) - Unary Operators (
+x,-x,~x) - Assignment Operators (
=,+=,-=,*=, etc.) - Ternary Expression (
if else) — evaluated right to left
Examples of Right-to-Left Associativity
Example 1: Exponent
2 ** 3 ** 2
Evaluated as:
2 ** (3 ** 2)
→ 2 ** 9
→ 512
Example 2: Assignment
x = y = z = 10
Evaluates as:
x = (y = (z = 10))
So all get value 10.
Example 3: Unary
x = - - 5
Right to left:
x = -(-5)
x = 5
3. Associativity Summary Table
| Operator Type | Operators | Associativity |
|---|---|---|
| Exponent | ** | Right-to-left |
| Unary | +x, -x, ~x | Right-to-left |
| Assignment | =, +=, -=, etc. | Right-to-left |
| Multiplicative | *, /, %, // | Left-to-right |
| Additive | +, - | Left-to-right |
| Bitwise Shift | <<, >> | Left-to-right |
| Bitwise | &, ^, ` | ` |
| Comparison | <, >, <=, >=, ==, != | Left-to-right |
| Logical | and, or | Left-to-right |
4. Examples for Practice
Example 1:
100 // 5 // 2
Left to right:
(100 // 5) // 2 = 20 // 2 = 10
Example 2:
10 ** 2 ** 2
Right to left:
10 ** (2 ** 2) = 10 ** 4 = 10000
Example 3:
a = b = c = 5
Right to left → all get 5.
Example 4:
not False or True
Left to right:
(not False) or True
True or True = True
Conclusion
- Precedence decides which operator is evaluated first.
- Associativity decides direction (left or right) when operators have same precedence.
- Most operators are left-to-right, while
**and assignments are right-to-left.
