Precedence and Associativity of Operators in Python
When dealing with operators in Python we have to know about the concept of Python operator precedence and associativity as these determine the priorities of the operator otherwise, we’ll see unexpected outputs.
Operator Precedence: This is used in an expression with more than one operator with different precedence to determine which operation to perform first.
10 + 20 * 30
10 + 20 * 30 is calculated as 10 + (20 * 30) and not as (10 + 20) * 30
Example: Now, let’s see an example on logical ‘or‘ & logical ‘and‘ operator. ‘if‘ block is executed even if the age is 0. Because precedence of logical ‘and‘ is greater than the logical ‘or‘.
Hence, To run the ‘else‘ block we can use parenthesis( ) as their precedence is highest among all the operators.
Operator Associativity: If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.
Example: ‘*’ and ‘/’ have the same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
100 6 0 512
Operators Precedence and Associativity are two main characteristics of operators that determine the evaluation order of sub-expressions in absence of brackets.
100 + 200 / 10 - 3 * 10
100 + 200 / 10 - 3 * 10 is calculated as 100 + (200 / 10) - (3 * 10) and not as (100 + 200) / (10 - 3) * 10
Please see the following precedence and associativity table for reference. This table lists all operators from the highest precedence to the lowest precedence.
|* / %||Multiplication/division/modulus||left-to-right|
|<< >>||Bitwise shift left, Bitwise shift right||left-to-right|
|< <= |
|Relational less than/less than or equal to |
Relational greater than/greater than or equal to
|== !=||Relational is equal to/is not equal to||left-to-right|
is, is not
in, not in
|^||Bitwise exclusive OR||left-to-right|
||||Bitwise inclusive OR||left-to-right|
Modulus/bitwise AND assignment
Bitwise exclusive/inclusive OR assignment
Bitwise shift left/right assignment