Python

Precedence and Associativity of Operators in Python

In the following article, python precedence and associativity of operators which are used to evaluate an expression with multiple operators are discussed in detail along with examples.

Precedence of Python Operators

An expression is a collection of values, variables, operators and function calls that can be evaluated by python interpreters if the expression is valid.

For example:

Code

Explanation

Here 6-10 is an expression with – operator.

An expression can be more complex with more than one operator. To evaluate such complex expressions, there is a rule of precedence in python which guides the order of evaluation in case of multiple operators.

For example, multiplication has higher precedence than addition.

Code

                    

# Multiplication has higher precedence than addition

a = 10 + 4*5

print(a)

Output

30

This order can be changed by using brackets as brackets have higher precedence than division.

Code

                    

# Brackets have higher precedence than division

a = (10 + 4)*5

print(a)

Output

70

The precedence order for operators in python is listed below in the following table. The operator in the upper group has higher priority or precedence than the lower one.

Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, – Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
not Logical NOT
and Logical AND
or Logical OR

 

For example, in the code below the precedence of ‘and’ is more than the precedence of ‘or’ so it is evaluated first. So name == “Bob” and age >= 40 will be False and then name == “Apoyo” or False will be True and hence the output is Hello! Welcome to this world.

Code

                    

# Precedence of ‘and’ and ‘or’

name = “Apoyo”

age = 21

if name == “Apoyo” or name == “Bob” and age >= 40 :

print(“Hello! Welcome to this world.”)

else :

print(“Good Bye!”)

Output

Hello! Welcome to this world.

If we want to print the else part then we have to use parenthesis () since they have the highest precedence. Now in this case, (name == “Apoyo” or name == “Bob”) this part will evaluate to true but age >= 40 is false and hence and operator between these two will result in false and output will be Good Bye!.

Code

                    

# Precedence of ‘and’ and ‘or’

name = “Apoyo”

age = 21

if (name == “Apoyo” or name == “Bob”) and age >= 40 :

print(“Hello! Welcome to this world.”)

else :

print(“Good Bye!”)

Output

Good Bye!

Associativity of Python Operators

In the above table, it can be seen that more than one operator exists in the same group, that is some operators have the same precedence.

In such cases when operators have the same precedence, associativity is used to determine the order of evaluation of operators.

Associativity is defined as the order according to which an expression with multiple operators of the same precedence is evaluated. Generally all the operators have left to right associativity.

For example, floor division and multiplication have the same precedence. Hence, if both floor division and multiplication operators are present in an expression, the left one is evaluated first.

Code

                    

# Left-right associativity

print(6 * 5 // 2)

 

# Shows left-right associativity

print(6 * (5 // 2))

Output

15

12

In the code above initially 6*5 (=30) was evaluated first and hence 15 (30//2) was printed as the output. Then we added parentheses around 5//2 so as parentheses have more precedence than multiplication 5//2(=2) was evaluated first and then 12 (6*2) was printed as the output.

Non associative operators

Some of the operators like assignment operators and comparison operators do not have any associativity order in python, hence they have separate rules for evaluating expressions with these kinds of operators which cannot be expressed as associativity.

For example, the expression a > b > c  neither means (a > b) > c nor a > (b > c). So the expression a > b > c  is basically equivalent to a>b and b>c and is evaluated from left to right.

Code

                    

# Initialize variables a, b, c to 1

a = b = c = 1

# Expression is invalid (Non-associative operators)

# SyntaxError: invalid syntax

a = b = c+= 2

Output

Invocation failed [COMPILATION_ERROR]

Can’t compile file:

Traceback (most recent call last):

File “<string>”, line 1, in <module>

File “11236.py”, line 6

a = b = c+= 2

We cannot chain the addition operator with multiple assignment operators, but chaining of assignments like a = b = c = 0 is perfectly valid.

Frequently Asked Question:

 Q.1. What is the order of precedence in python of 1 parentheses 2 exponential?

Answer: The order of precedence for parenthesis is more than that of exponential. Suppose we have an expression containing both parenthesis and exponential:

Code

                    

# exponential has higher precedence than addition

a = 5 + 3 ** 2

print(a)

# parenthesis has higher precedence over exponential

a = (5 + 3) ** 2

print(a)

In the code above initially 3**2(=9) was evaluated first and hence 14 (5+9) was printed as the output. Then we added parentheses around 5+3 so as parentheses have more precedence than exponential 5+3(=8) was evaluated first and then 64 (8**2) was printed as the output.

Output

14

64

Q.2. What is the correct order of precedence?

Answer: The correct order of precedence is given by PEMDAS which means Parenthesis (), Exponential **, Multiplication *, Division /,  Addition +, Subtraction -. Some expressions have multiple operators, to evaluate such complex expressions, there is a rule of precedence in python which guides the order of evaluation in case of multiple operators.

In case some operators have the same precedence level, associativity is used to determine the order of evaluation of operators.

Associativity is defined as the order according to which an expression with multiple operators of the same precedence is evaluated. Generally all the operators have left to right associativity.

Q.3. What is the order of operations in Python?

Answer: The precedence order for operators in python is listed below in the following table. The operator in the upper group has higher priority or precedence than the lower one.

Operators Meaning
() Parentheses
** Exponential operator
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, – Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
not Logical NOT
and Logical AND
or Logical OR

 

Q.4. Which operator in Python has the lowest precedence?

Answer: The Logical OR operator has the lowest precedence in python. Let’s look at an example involving Logical OR operator:

Code

                    

# Precedence of ‘and’ and ‘or’

name = “Apoyo”

if name == “Apoyo” or name == “Bob” and 5+2 == 6:

print(“Hello! Welcome to this world.”)

else :

print(“Good Bye!”)

Output

Hello! Welcome to this world.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Browse

Python
  • Precedence and Associativity of Operators in Python

Leave a Reply

Your email address will not be published. Required fields are marked *

Browse

Python
  • Precedence and Associativity of Operators in Python

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.