3 min read•june 24, 2024
Python's associativity rules are crucial for writing accurate expressions. These rules determine how complex calculations are broken down and executed. Understanding them helps you write clearer code and avoid unexpected results.
Parentheses, , multiplication/division, and addition/subtraction form the basic hierarchy. Comparison and have their own precedence levels. Associativity further refines how operators of equal precedence are evaluated, with most being left-associative except for exponentiation.
(2 + 3) * 4 = 20
[**](https://www.fiveableKeyTerm:**)
) has the highest precedence among 2 ** 3 = 8
*
), division (/
), floor division ([//](https://www.fiveableKeyTerm://)
), and ([%](https://www.fiveableKeyTerm:%)
) have equal precedence and perform from left to right 6 * 5 / 2 = 15
+
) and subtraction (-
) have equal precedence and perform from left to right 5 + 3 - 2 = 6
==
, !=
, <
, >
, <=
, >=
) have lower precedence than but higher than logical operators 3 + 4 < 5 + 6
evaluates to True
and
, [or](https://www.fiveableKeyTerm:Or)
, [not](https://www.fiveableKeyTerm:not)
) have lower precedence than , with not
having the highest precedence among them True and False or True
evaluates to True
a - b - c
equals (a - b) - c
a ** b ** c
equals a ** (b ** c)
10 - 5 + 3
evaluates as (10 - 5) + 3 = 8
due to left associativity**
) is right-associative
2 ** 3 ** 2
evaluates as 2 ** (3 ** 2) = 512
due to right associativity8 / 4 * 2
equals 4
, not 1
(3 + 4) * 2 = 14
((2 + 3) * 4) - 5
evaluates as (2 + 3)
first, then multiplies by 4
, and finally subtracts 5
x * (y + z)
is more readable than x * y + x * z
, even though they are equivalent10 + 20 * 30 ** 2
can be written as 10 + (20 * (30 ** 2))
to make the order explicit0 < x < 10
is equivalent to 0 < x and x < 10