Operator Precedence
4 min read ·
Operator precedence in Python defines the order in which operators are evaluated in an expression.
When an expression contains multiple operators, Python follows a fixed priority order to decide which operation is performed first.
Understanding operator precedence is essential to avoid logical bugs and unexpected results.
What Is Operator Precedence?
Operator precedence determines:
- Which operator is evaluated first
- How complex expressions are solved
- Why some expressions give unexpected output
Output is
20, not 30, because * has higher precedence than +.Why Operator Precedence Matters
Without knowing precedence:
- Expressions may produce wrong results
- Conditions may behave incorrectly
- Debugging becomes difficult
Operator Precedence Order (High to Low)
The table below shows Python operator precedence from highest to lowest.
| Precedence | Operator | Description |
|---|---|---|
| 1 | () | Parentheses |
| 2 | ** | Exponentiation |
| 3 | +x, -x, ~x | Unary operators |
| 4 | *, /, //, % | Multiplication, Division |
| 5 | +, - | Addition, Subtraction |
| 6 | <<, >> | Bitwise shifts |
| 7 | & | Bitwise AND |
| 8 | ^ | Bitwise XOR |
| 9 | | | Bitwise OR |
| 10 | <, <=, >, >=, ==, != | Comparisons |
| 11 | not | Logical NOT |
| 12 | and | Logical AND |
| 13 | or | Logical OR |
| 14 | = | Assignment |
Parentheses (())
Parentheses have the highest precedence and are used to control evaluation order.
Exponentiation (**)
Exponentiation is evaluated before multiplication and addition.
Arithmetic Precedence
Unary Operators
Unary operators apply to a single operand.
Comparison Precedence
Comparisons are evaluated after arithmetic operations.
Logical Operator Precedence
Logical operators have lower precedence than comparisons.
Chained Comparison Precedence
Chained comparisons are evaluated left to right.
Bitwise Operator Precedence
Assignment Precedence (Lowest)
Assignment has the lowest precedence.
Common Mistakes
Assuming Left-to-Right Always
This is evaluated as:
Forgetting Parentheses
Best Practice
Always use parentheses when:
- Expression is complex
- Readability matters more than brevity
- Logical conditions are combined
Practice
- Predict output of mixed expressions
- Rewrite expressions using parentheses
- Identify precedence errors in conditions
- Convert complex expressions into readable form