Operator Precedence
-
Operator Precedence in Python defines the hierarchy in which operators are evaluated in expressions. This lesson explains which operators are executed first and how Python applies associativity when multiple operators have the same level of precedence.
Operator precedence defines the order in which operators are evaluated in an expression.
Operators with higher precedence are evaluated before operators with lower precedence.
If operators have the same precedence, Python follows associativity rules to decide the evaluation order.
Operator Precedence Table (High → Low)
Operator Precedence Example
Demonstrates how Python evaluates expressions based on precedence.
result = 10 + 5 * 2
print(result)
Explanation:
* has higher precedence than +
So, 5 * 2 = 10
Then, 10 + 10 = 20
Using Parentheses
result = (10 + 5) * 2
print(result)
Explanation:
Parentheses are evaluated first
10 + 5 = 15
15 * 2 = 30
Associativity Rules
Associativity decides the evaluation direction when two or more operators of the same precedence appear in an expression.
Associativity
result = 2 ** 3 ** 2
print(result)
Explanation:
** follows right-to-left associativity
So, 3 ** 2 = 9
Then, 2 ** 9 = 512