Operator Precedence and Associativity
When multiple operators are used in a single expression, Python has a strict set of rules to determine the order in which they are evaluated. This is known as operator precedence. It’s similar to the order of operations (PEMDAS/BODMAS) you learned in math class.
Operator Precedence Table
Here is a summary of Python’s operator precedence, from highest (evaluated first) to lowest (evaluated last).
Precedence | Operator | Description |
---|---|---|
Highest | () [] {} | Parentheses, List/Dict/Set displays |
x[index] , x.attr | Subscriptions, Attribute access | |
await x , f() | Await expression, Function calls | |
** | Exponentiation | |
+x , -x , ~x | Unary plus, minus, and bitwise NOT | |
* , / , // , % | Multiplication, Division, Modulus | |
+ , - | Addition and Subtraction | |
<< , >> | Bitwise shifts | |
& | Bitwise AND | |
^ | Bitwise XOR | |
` | ` | |
in , not in , is , is not , < , <= , > , >= != , == | Comparisons, Identity, Membership | |
not x | Boolean NOT | |
and | Boolean AND | |
or | Boolean OR | |
if...else | Conditional expression | |
lambda | Lambda expression | |
Lowest | := | Assignment expression (Walrus) |
Rule #1: Use Parentheses!
You don’t need to memorize this entire table. The best practice is to use parentheses ()
to explicitly group operations. This makes your code’s intent clear to human readers and guarantees the correct order of evaluation.
Evaluation Example
Let’s see how Python evaluates a complex expression based on these rules.
Pyground
Evaluate the expression `10 + 5 * 3 ** 2`.
Expected Output:
The result is: 55
Output:
Using Parentheses to Change Order
Now, see how adding parentheses changes the outcome completely.
Pyground
Evaluate `(10 + 5) * 3 ** 2`.
Expected Output:
The result is: 135
Output:
Associativity
When operators have the same precedence, associativity determines the order of evaluation. Most operators in Python are left-to-right associative.
5 - 3 + 1
is evaluated as(5 - 3) + 1
=>2 + 1
=>3
.
The main exception is the exponentiation operator **
, which is right-to-left associative.
Pyground
Demonstrate the right-to-left associativity of the exponentiation operator.
Expected Output:
2 ** 3 ** 2 = 512 (2 ** 3) ** 2 = 64
Output:
Short-Circuiting in Logical Operators
The logical operators and
and or
also follow precedence rules, but they have a special property called short-circuiting. The evaluation stops as soon as the result is known.
Pyground
Demonstrate short-circuiting where an error-producing function is never called.
Expected Output:
The expression evaluated to: True The expression evaluated to: False