Skip to main content

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.

Operators Description
() Parentheses
** Exponent
~ a, +b , -a Bitwise 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 in Logical ,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
Submitted by devanshi.srivastava on June 26, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.