Today we’ll be talking about the precedence of operators.
Here’s the video version of this article:
Some operators are more important than others, at least in terms of precedence. Here we have all the operators from highest to lowest precedence:
1 | () | Parentheses |
2 | ** | Exponentiation |
3 | ~ + – | Complement Unary Plus Unary Minus |
4 | * / // % | Multiplication True Division Floor Division Modulus |
5 | + – | Addition Subtraction |
6 | >> << | Right Bitwise Shift Left Bitwise Shift |
7 | & | Bitwise AND |
8 | ^ | Bitwise Exclusive OR (XOR) |
9 | | | Bitwise OR |
10 | < <= > >= | Comparison Operators |
11 | == != | Equal To Not Equal To |
12 | = += -= *= /= //= %= **= | Assignment Operators |
13 | is is not | Identity Operators |
14 | in not in | Membership Operators |
15 | not | Logical not |
16 | and | Logical and |
17 | or | Logical or |
Operators with higher precedence work first, so for example in the following example first 3 and 2 are multiplied and then the product is added to 7. This is because multiplication is higher in the precedence hierarchy than addition.
>>> 7 + 3 * 2
13
Now a totally different example:
>>> 3 ** 2 * 5 % 2 // 4 / 2 <= -1 * 2
False
Let’s analyze it step by step:
Of all the operators here exponentiation is the one with the highest precedence. It’s carried out first. Now we have:
9 * 5 % 2 // 4 / 2 <= -1 * 2
The next in the hierarchy is the unary minus, so we have a negative 1:
9 * 5 % 2 // 4 / 2 <= (-1) * 2
And then we have multiplication, true division, floor division and modulus, all on the same level in the hierarchy, so they are used in the order of appearance:
0.0 <= -2
which is false.
Use Parentheses
It’s extremely easy to lose track of what’s going on and in which order with such complicated expressions. That’s why we should use parentheses as much as possible. They are the highest in the precedence hierarchy. It’s advisable to use them even if it’s not necessary, just to make it clearer.
Here are a few expressions with parentheses in different places. The result is different each time because the operators are applied according to the placement of the parentheses:
>>> 5 + 2 ** 3 / 3
7.666666666666666
>>> (5 + 2) ** 3 / 3
114.33333333333333
>>> 5 + 2 ** (3 / 3)
7.0
>>> (5 + 2 ** 3) / 3
4.333333333333333
>>> (5 + 2) ** (3 / 3)
7.0