Precedence and Associativity of Operators in Python

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

OperatorDescriptionAssociativity
( )Parenthesesleft to right
**Exponentright to left
~ + –Complement, unary plus and minusright to left
* / % //Multiplication / division / modulus / floor divisionleft to right
+ –Addition / subtractionleft to right
<< >>Bitwise left shift / Bitwise right shiftleft to right
< <=
> >=
Relational operators: less than / less than or equal to / greater than / greater than or equal toleft to right
== !=Relational operators: is equal to / is not equal toleft to right
is, is not, in, not inIdentity operatorsMembership operatorsleft to right
&Bitwise AND operatorleft to right
^Bitwise exclusive OR operatorleft to right
|Bitwise inclusive OR operatorleft to right
notLogical NOTright to left
andLogical ANDleft to right
orLogical ORleft 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
error: You can only copy the programs code and output from this website. You are not allowed to copy anything else.