Precedence: It gives the order of execution of operators in an expression i.e. gives an idea about which operator is to be executed first when there are multiple operators in an expression.
Example: The expression 4+3 * 2 can be solved by two ways. But only way1 is correct
Way 1) 4+3 * 2
=4+6 (3 * 2 is evaluated first)
=10
Way 2) 4+3*2
= 7*2 (4 + 3 is evaluated first)
= 14
Associativity: It tells the order whether left to right (L → R) or right to left (R → L) in which the operators of same precedence will be executed in an expression.
Example: 12 /4 *3 can be solved by two ways. But only way1 is correct because associativity is L->R for multiplication and division
Way 1) 12/4 *3
=3 * 3 (12/4 is evaluated first)
=9
Way 2) 12/4 *3
=12/12 (4 * 3 is evaluated first)
=1
Precedence and Associativity of Various Operators in Python Language The operators precedence is from highest to lowest from top to bottom respectively in the below table. Only 3 operators ie ** , (unary +, unary- , ~) and (assignment & augmented assignment) operators have right to left associativity. All other operators have left to right associativity. Python uses PEMDAS rule for precedence.
P – Parentheses
E – Exponentiation
M – Multiplication
D – Division
A – Addition
S – Subtraction
Operator | Description | Associativity |
---|---|---|
( ) | Parentheses | left to right |
** | Exponent | right to left |
~ + – | Complement, unary plus and minus | right to left |
* / % // | Multiplication / division / modulus / floor division | left to right |
+ – | Addition / subtraction | left to right |
<< >> | Bitwise left shift / Bitwise right shift | left to right |
< <= > >= | Relational operators: less than / less than or equal to / greater than / greater than or equal to | left to right |
== != | Relational operators: is equal to / is not equal to | left to right |
is, is not, in, not in | Identity operatorsMembership operators | left to right |
& | Bitwise AND operator | left to right |
^ | Bitwise exclusive OR operator | left to right |
| | Bitwise inclusive OR operator | left to right |
not | Logical NOT | right to left |
and | Logical AND | left to right |
or | Logical OR | left to right |
= += -= *= /= //= **= %= &= ^= |= <<= >>= | Assignment operators: Addition / subtraction Multiplication / division floor division/ power Modulus / bitwise AND Bitwise exclusive / inclusive OR Bitwise shift left / right shift | right to left |
>>># ** has more precedence. So 1 ** 3 = 1 is evaluated first, and then 3 * 1 = 3 >>> 3 * 1 ** 3 3 >>># () has more precedence. So ( 3*1 = 3)is evaluated first, and then 3 ** 3 = 27 >>> ( 3*1 ) ** 3 27 >>># ** has Right to left associativity. So 1 ** 3 = 1 is evaluated first, and then 3 ** 1 = 3 >>> 3 ** 1 ** 3 3