Operator Precedence and Associativity in Python

In this class, we discuss operator precedence and associativity in python.

For Complete YouTube Video: Click Here

We discussed all the operators present in python in our previous class. press here for operators.

Precedence in Python

First, check the operator precedence and associativity chart given below.

Operator Precedence and Associativity in Python
Precedence and Associativity Table

From the above chart, it was given the topmost operators are given the highest precedence.

The precedence from top to bottom decreases. means the lowest operator in the chart has the lowest precedence

Let’s take an example and understand what precedence means.

Take the expression 2+5*2.

In order to evaluate the expression, we can do in two ways.

First do addition ie 2+5 = 7. Then do multiplication 7*2 = 14.

The other way first do multiplication ie 5*2 =10. then do addition 2+10 =12.

We got different answers, to avoid confusion we have to follow a particular order.

This order is followed according to precedence. the operator having the highest precedence will execute first.

From our example and the precedence char given above. multiplication operator has the highest precedence.

Multiplication is done first. the result is added with 2.

From the above chart, the operators present at the same level are having the same precedence.

Multiplication, division, modulus, and floor division all are at the same level. so same precedence.

With this understanding, we will check what is associativity means.

Associativity

Let’s take an example and understand the need for associativity.

Example: 2+5*2*2/5.

How to evaluate the expression?

The above expression had both multiplication and division.

Both are having the same precedence. so which one should be evaluated first?

Here comes the concept of associativity. In the table, it was given associativity as left to right.

The expression evaluates from left to right. ie 5*2 evaluates first, the result is 10.

10*2 is evaluated next. the result is 20. 20/5 is evaluated next, the result is 4. The last 2+4 will be done.

The final output is 6.

Few more examples.

print(2**3**2) the output is 512.

Here power is having a right to left associativity. so 3**2 is evaluated first, the output is 9.

Now 2**9 is evaluated which results in 512.

Deviations in associativity

Take example: x=5,y=6,z=7.

print(x<y<z). this should be evaluated x<y first the result is true. means 1.

Now 1<z should be evaluated according to associativity.

But it evaluates like x<y and y<z.

Which results in true.

Take one more example.

x=5,y=5,z=5.

print(x is y is z). this evaluates as x is y and y is z. which gives true.