Table of Contents
ToggleIn Python, expressions often contain multiple operators, and the order in which these operators are evaluated can significantly impact the result. This order is determined by operator precedence. Understanding operator precedence is crucial for writing accurate and efficient Python code. In this blog, we’ll explore what operator precedence is, how it works, and provide practical examples to help you master this concept.
Operator precedence defines the order in which operators are evaluated in an expression. For example, consider the expression:
a = 2 + 3 * 5
What will be the value of a? Will it be 17 (multiply 3 by 5 first and then add 2) or 25 (add 2 and 3 first and then multiply by 5)? Python’s operator precedence rule resolves this ambiguity. Since multiplication has higher precedence than addition, a will be 17.
Python follows the traditional BODMAS rule (Brackets, Orders, Division, Multiplication, Addition, Subtraction) for arithmetic operations. This means:
For example, in the expression 2 + 3 * 5, multiplication is performed before addition, resulting in 17.
When an expression contains operators with the same precedence, the order of evaluation is determined by associativity. Most operators in Python have left-to-right associativity, meaning the leftmost operator is evaluated first.
For example, consider the expression:
b = 10 / 5 * 4
Both / (division) and * (multiplication) have the same precedence. Due to left-to-right associativity, division is performed first (10 / 5 = 2), followed by multiplication (2 * 4 = 8). Thus, b will be 8.
Below is a table listing Python operators in order of their precedence (from highest to lowest). Operators in the same row have the same precedence and are evaluated from left to right.
| Precedence | Operator | Description |
|---|---|---|
| 1 | (), [], {} |
Parentheses, Brackets, Braces |
| 2 | ** |
Exponentiation |
| 3 | *, /, //, % |
Multiplication, Division, Floor Division, Modulus |
| 4 | +, - |
Addition, Subtraction |
| 5 | <<, >> |
Bitwise Shifts |
| 6 | & |
Bitwise AND |
| 7 | ^ |
Bitwise XOR |
| 8 | | |
Bitwise OR |
| 9 | ==, !=, >, <, >=, <= |
Comparison Operators |
| 10 | not |
Logical NOT |
| 11 | and |
Logical AND |
| 12 | or |
Logical OR |
Understanding Python operator precedence is essential for writing accurate and efficient code. By following the rules of precedence and using parentheses to override them when necessary, you can ensure that your expressions are evaluated as intended. Keep practicing with different examples to master this concept and become a more proficient Python programmer!
