
When there are operators of the same precedence in an arithmetic operation, Python follows a specific rule called associativity to determine the order of evaluation.
Associativity defines the direction in which operations of the same precedence are processed:
Most arithmetic operators in Python (like
+,-,*,/) are left-associative, meaning they are evaluated from left to right.Some operators, like exponentiation (
**), are right-associative, meaning they are evaluated from right to left.
Example 1: Left-to-right associativity (for - and /)
result = 20 - 5 - 2 # evaluated as (20 - 5) - 2 = 13
print(result) # Output: 13Example 2: Right-to-left associativity (for **)
result = 2 ** 3 ** 2 # evaluated as 2 ** (3 ** 2) = 2 ** 9 = 512
print(result) # Output: 512If you're ever unsure, you can use parentheses to make the order of operations explicit. For example:
# Force a different order
result = (20 - (5 - 2)) # result is 17If you want to learn more about this, I recommend checking out the blog Understanding Operator Precedence and Associativity in Python. It explains this concept in a clear and structured way.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer