Python: Operator Precedence and Associativity

Operator Precedence

It is used in an expression with more than one operator with different precedence to determine which operation to perform first.

The operator precedence in Python is listed in the following table. It is in descending order.

OperatorsDescription
()Parentheses
**Exponent
~ a, +b , -aBitwise NOT, Unary plus and minus
*, /, %, //,Multiplication, Division, Floor division, Modulus
+,-Addition, Subtraction
<<,>>Right and Left Bitwise Shift Operators
&AND
^,|Bitwise XOR ,Bitwise OR
<=,< >,>=Comparison Operators
< >,==,!=Equality Operators
= ,%=, /= ,//= ,-=, +=, *= ,**=Assignment Operators
not, or, and, is is not, in ,not inLogical ,Identity & Membership Operators

Example:

a = 10 
b = 40
c = 30
d = 50

expr_1 = (a + b) * c / d
expr_2 = a + b * c / d

print("expr_1 = ",expr_1)
print("expr_2 = ",expr_2)

Output:

expr_1 =  30.0
expr_2 =  34.0

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:

print(2 ** 3 ** 2)
print(5 - 2 + 3)
print(5 * 2 // 3)

print(2 ** (3 ** 2))
print(5 - (2 + 3))
print(5 * (2 // 3))

Output:

512
6
3
512
0
0

These two are main characteristics of operators that determine the evaluation order of sub-expressions in absence of brackets.

Tags