In one of my previous articles we were talking about the precedence of operators.
Today we’ll be talking about operator associativity. This is about the order of evaluation of operators.
Here’s the video version of this article:
Some operators share the same level of precedence with other operators, like for example multiplication and modulus. Such operators are evaluated from left to right. One exception is the exponent operator, which is evaluated in the opposite direction. The order in which operators are evaluated in an expression is called operator associativity. So, in most cases we have left-to-right associativity and in the case of the exponent operator we have right-to-left associativity.
Here are some examples:
Here the order is from left to right:
>>> 3 * 4 % 5 # 12 % 5 = 2
2
We can change the order by using parentheses:
>>> 3 * (4 % 5) # 3 * 4 = 12
12
Again from left to right:
>>> 3 % 4 * 5 # 3 * 5 = 15
15
And again we can use parentheses to change the order:
>>> 3 % (4 * 5) # 3 % 20 = 3
3
And now the exponent operator. This one is evaluated from right to left:
>>> 2 ** 3 ** 2 # 2 ** 9 = 512
512
If you need a different order, the parentheses are a solution:
>>> (2 ** 3) ** 2 # 8 ** 2 = 64
64