Python - Things to know before proceed - Precedence & Associativity Of Operator Tutorial
Precedence
In Expression, there can be one or more operators. To evaluate such type of expression there is the rule of Precedence in python
For example:-
Let consider an expression 10 + 5 * 3.
In the above expression * (multiplication) has higher precedence than + (addition).but we can change the order using parenthesis, as it has higher precedence than multiplication.
i.e (10 + 5) * 3
Precedence Table ( Precedence in the below table will be in descending order. Upper Operator has higher precedence.)
Operator |
Name as |
Associativity |
( ) |
Parenthesis |
Left To Right |
** |
Exponent |
Right To Left |
+x , -x , ~x |
Unary plus, Unary minus, Bitwise NOT |
Left To Right |
* , / , // , % |
Multiplication, Division, Floor division, Modulus |
Left To Right |
+ , - |
Addition, Subtraction |
Left To Right |
<< , >> |
Bitwise shift operators |
Left To Right |
& |
Bitwise AND |
Left To Right |
^ |
Bitwise XOR |
Left To Right |
| |
Bitwise OR |
Left To Right |
== , != , > , >= , < , <= , is , is not , in , not in |
Comparisons, Identity, Membership operators |
Left To Right |
not |
Logical NOT |
Left To Right |
and |
Logical AND |
Left To Right |
or |
Logical OR |
Left To Right |
( 2 + 6 ) * ( 10 - 8 ) / 2 ** 3 % ( 5 // 2)Example:-
( 8 ) * ( 2 ) / 2 ** 3 % ( 2 ) #First Priority to Parenthesis
8 * 2 / 8 % 2 #Then exponent
16 / 8 % 2 #Then multiplication
2 % 2 #Then modulus
0
Associativity
Suppose in an expression, all the operators are of the same precedence, then associativity helps to determine the order of expression. Almost all operators have Left to Right associativity. Some of them have Right to Left associativity.
For example:-
3 + 2 + 1 #It has Left to Right associativity
6
Another example with Right to Left associativity:-
3 ** 2 ** 3 #It will solve first 2 ** 3
3 ** 8
6561