Reading Time: 1 minutes
Operator Precedence in Python
Following is the order in which operators in Python are evaluated. The operators at the top are evaluated first, and ones lower down the order are evaluated later.
Operator(s) | Name of Operator(s) |
---|---|
() | Parentheses |
** | Exponentiation |
+a, -a, ~a | Positive, negative, bitwise NOT |
*, /, //, % | Multiplication, division, floor division, modulus |
+, - | Addition, subtraction |
<<, >> | Shifts |
& | Bitwise AND |
^ | Bitwise XOR |
| | Bitwise OR |
in, not in, is, is not, <, <=, >, >=, !=, == | Membership, identity & comparisons |
not a | Boolean NOT |
and | Boolean AND |
or | Boolean OR |
Note that there are cases when 2 or more operators have the same precedence e.g. *, /. If a Python expression has multiple operators of the same precedence, the order of evaluation in such cases is left to right. The one occurring on the left is evaluated first. For example:
>>> 2 * 8 / 4 # (2 * 8) / 4 4.0 >>> 2 / 8 * 4 # (2 / 8) * 4 1.0
The exception to left-to-right order is the exponent operator, which has right-to-left associativity.
>>> 2 ** 2 ** 2 # 2 ** (2 ** 2) 16