In this article, you’ll learn**:**

**1.** What are precedence and associativity of operators in python

**2.** How they affect the order of operations (with examples)

**3.** Need of precedence and associativity of operators

**4.** How do you remember operator precedence in python? (short trick)

So, Let’s get started!

Before we move further,

Let’s have a quick look on some important terms, so that you’ll understand all the upcoming concepts easily and feel confidence as you move forward.

And, the terms which I’m talking about are**:** **Expressions**, and **Evaluation of an expression**.

**Expression:** An **Expression** is a sequence or combination of values, variables, **operators** and function calls that always produces or returns a result value.

If you type an expression on the** IDLE** or on the **command line**, the interpreter **evaluates** it and displays the result.

**Example:** `x = 5`

, `y = 3`

, `z = x + y`

In the above example `x`

, `y`

and `z`

are variables, `5`

and `3`

are values, `=`

and `+`

are operators.

So, the first combination `x = 5`

is an expression, the second combination `y = 3`

is an another expression and at last, `z = x + y`

is also an expression.

**Evaluation of an expression:** It simply means that, to calculate or to solve the value of something. Such as in the above example**:** `z = x + y`

, which is equivalent to `z = 5 + 3`

. So, here we are calculating the value of `z`

. and, hence, `z = 8`

.

**Sorry!** (for taking your more time)

But, I want you to understand every single stuff better.

So, May I ask two rapid question!

**Question 1: **What will be the output of this expression**:** `2 + 3 `

Your answer is` 5`

, **right…?**

Ya, you are correct. That’s so simple.

Now,

**Question 2:** Guess the output of the expression given below**?**

Done?

What is your answer?

Is it` 4`

or is it `14`

?

If your answer is `4`

, then you are correct, and if your answer is `14`

, then you are wrong.

I know, I know… the person who got the answer` 14`

might be wondering that why `14`

is wrong and why** **`4`

is correct.

**Explanation:** `14`

is wrong because, those who got `14`

then, he/she must have solved the expression according to the following way**: **

He/she definitely added `6`

and `4`

first, then subtracted the result (i.e., `6 + 4 = 10`

) by `3`

and at last multiplied the result (i.e., `10 - 3 = 7`

) by `2`

. Which will give `14`

as an output.

But, the answer is wrong. Why? – because, it has not been evaluated according to the order as like the operators are evaluated in python.

And, to overcome this problem, Precedence of operators comes into picture.

So,

When an expression contains more than one operator, then we need to decide which operator will be evaluated first.

The set of rules which gives the priority (precedence) of operators while evaluating an expression is known as operator precedence.

So, There is a rule of precedence (priority) in python which gives the order/sequence in which various operation are performed in an expression according to the priority of operators is known as hierarchy of operations or operator precedence.

Precedence rules decides the order in which different operators are applied in an expression.

The operators at the higher level of precedence are evaluated first.

? The following table summarizes the operator precedence in Python. It is in descending order (upper group has higher precedence than the lower ones). Operators in the same box have the same precedence.

### Python operator precedence table:

Operator | Description (Meaning) |
---|---|

(expressions... ) [expressions...], {key: value...}, {expressions...} | Parenthesized expression, list display, dictionary display, set display |

x[index], x[index:index], x(arguments...), x.attribute | Subscription, slicing, call, attribute reference |

await x | Await expression |

** | Exponent |

+x, -x, ~x | Unary plus (positive), Unary minus (minus), bitwise NOT |

*, @, /, //, % | Multiplication, Matrix multiplication, Division, Floor division, Modulus |

+, - | Addition, Subtraction |

<<, >> | Bitwise left shift, Bitwise right shift |

& | Bitwise AND |

^ | Bitwise XOR |

| | Bitwise OR |

in, not in, is, is not, <, <=, >, >=, !=, == | Membership, identity and Comparison (Relational) operators |

not | Logical NOT |

and | Logical AND |

or | Logical OR |

if - else | Conditional expression |

lambda | Lambda expression |

:= | Assignment operators |

So, from the above table we can see that,

⚉ **Parentheses** has the **highest precedence** in python.

Since, expressions in parentheses are evaluated first, `3`

`* (5-2)`

is `9`

.

⚉ Exponentiation has the next highest precedence, so `2 + 3**3`

is `29`

, not `125`

.

⚉ Multiplication and Division have higher precedence than Addition and Subtraction.

So, `3*4-2 `

is `10`

, not` 6`

, and `5+6/2`

is `8`

, not `5.2`

⚉ **Assignment operator** has the **lowest** **precedence** in python.

⚉ Operators with the same precedence are evaluated from *left-to-right* (except exponentiation). So in the expression `degrees / 2 * pi`

, the division happens first and the result is multiplied by pi. To divide by `2*pi`

, you can use parentheses or write `degrees / 2 / pi`

.

**Let’s have a look at some of the examples:**

**Examples 1:**

**1.** Precedence of arithmetic operators**:**

An arithmetic expression without parentheses will be evaluated from *left-to-right* using the rules of precedence of operators.

There are two distinct priority levels of arithmetic operators in Python**:**

⚉ High priority**:** `*`

,` /`

,` //`

,` %`

⚉ Low priority**:** `+`

,` -`

The basic evaluation procedure includes ‘two’ **left-to-right** passes through the expression.

During the first pass, the high priority operators (if any) are applied as they are encountered. During the second pass, the low priority operators (if any) are applied as they are encountered.

Consider the following evaluation of an expression**:**

`9`

** - **12** /** 3 **+** 3 *** **2 **-** 1

The above expression is evaluated as follows**:**

**First pass**

** Step1:** `9 - `

~~12~~^{4}/~~3~~ + 3 * 2 -1 **=** `9 - 4 + 3 * 2 -1`

(Here, division has the highest priority. so, division between `12`

and `3`

happens first.)

** Step2:** ` 9 - 4 + 6 - 1`

(Then, multiplication between `3`

and `2`

)

**Second pass**

**Step3: ** `5 + 6 - 1`

(evaluated from left-to-right. because, + and – have the same priority, so addition between `5`

and `6`

happens first)

**Step4:** `11 - 1`

(evaluated from left-to-right)

**Step5:** `10`

However, the order of evaluation can be changed by introducing parentheses into an expression.

Consider the same expression (which we have taken in the above example) with parentheses as shown below**:**

`9 - 12 / (3 + 3) * (2 - 1)`

Whenever parentheses are used, the expressions within parentheses is suppose to highest priority.

If two or more sets of parentheses appear one after another as shown above, the expression contained in the left-most set is evaluated first and the right-most in the last.

The new steps are**:**

**First pass **

** Step1: ** `9 - 12 / 6 * ( 2 - 1)`

**Step2: **`9 - 12 / 6 * 1`

**Second pass**

**Step3:** `9 - 2 * 1`

(Multiplication between` 2`

and` 1 `

happens first. because, it has higher precedence than subtraction)

**Step4:** `9 - 2`

**Third pass**

** Step5: ** `7 `

This time, the procedure consists of three **left-to-right** passes. However, the number of evaluation steps remains the same as **5** (i.e., equal to the number of arithmetic operators).

Parentheses may be nested, and in such cases, evaluation of the expression will begin outward from the innermost set of parentheses.

**Points to be noted: **

Every opening parenthesis has a matching closing parenthesis.

For example**: ** `9 - (12 / (3 + 3) * 2) - 1 = 4`

Whereas, `9 - ((12 / 3) + 3 * 2) - 1 = -2`

### Advantages of using parentheses in an expression:

**–** Parentheses makes an expression easier to read and understand.

**Example:** As in (`minute * 100`

) `/ 60`

, even if it doesn’t change the result.

**– ** Parentheses can be used to force an expression to evaluate in the order you want.

**– **Parentheses allow us to change the order of priority.

**Example 2:**

**2.** Precedence of operators (belonging to two or more different groups)**:**

Let’s take a conditional statement**:** `if`

**( x**

`== 10 `

+` 15`

`and`

`y `

<` 5`

)The precedence rules say that the addition operator has a higher priority than the logical operator (`and`

) and the relational operators (**==** and** <**).

Therefore, the addition of `10`

and `15`

is evaluated first.

This is equivalent to**:** `if`

**( x**

`== 25`

`and`

`y `

<` 5`

)The next step is to determine whether `x`

is equal to `25`

and `y`

is less than` 5`

. If we assume a value of `18 `

for `x`

and `4 `

for` y`

, then

`x == 25`

is `FALSE`

`y < 5`

is `TRUE`

And, as we already know that** ==** and** <** operator has the same priority and evaluated from **left-to-right**, so, `x == 25`

is tested first and then `y< 5`

is tested.

Finally we get**:** if(`FALSE`

and `TRUE`

)

And, In `and`

operator, if one of the condition is `FALSE`

, then the complex condition is also `FALSE`

.

### Associativity of Python Operators:

If you look at the above precedence table, then you’ll find that more than one operator lies (exist) in the same box (group) or we can say they have same level of precedence.

**Example:** `*`

, `/`

, `//`

,` % `

are in the same box, which means that all these operators have the same precedence or same level of precedence.

Now, one question will definitely arises in your mind, that if all these operators (*****,** /**, **//**, **%**) has the same priority and if they all are encountered in a same expression, then which operator will be evaluated first.

To overcome this problem, Associativity of operators comes into picture.

So, Associativity of operators comes into picture when two or more operators have the same precedence and we need to decide which operator will be evaluated first.

Associativity rule decides the order in which multiple occurrences of the same level or we can say operator with same precedence are applied in an expression.

Associativity is the order/sequence in which an expression is evaluated that has two or more than two operators of the same precedence.

It can either be **left-to-right **or **right-to-left**.

But, here **–** What does ** left-to-right **or

*mean?*

**right-to-left**It simply means that, evaluation of an expression takes place from* left-to-right* hand side or

*hand side.*

**right-to-left**Associativity of all operators is from left-to-right (**except** for exponentiation and assignment operators which groups from right-to-left).

**Example 1:**

**1.** Associativity of arithmetic operator**:**

Let’s say: `x = 6 % 4 * 14 // 9 / 3`

Now, what will be the value of `x`

?

**Ans:** `x = 1`

**Explanation:** As we can see that the above expression (i.e.,` x = 6 % 4 * 14 // 9 / 3`

) contains all the operators (arithmetic operators) of same precedence.

And, we all know that arithmetic operators with the same precedence are evaluated from **left-to-right**. So in the expression**:** `x = 6 % 4 * 14 // 9 / 3`

, the modulo division (`%`

) happens first then the result is multiplied by `14`

then after multiplying by `14`

the result is divided (floor division) by `9`

and at last divided by `3`

.

Which will give `1 `

as an output.

**Example 2:**

**2.** Associativity of exponent operator**:**

Exponent operator (`**`

) has right-to-left associativity in python.

Now, Guess the output of**:** `3 ** 2 ** 2`

Output of the above expression (i.e., `3 ** 2 ** 2`

) is**:** `81`

**Explanation: **As we already know, that exponent has **right-to-left **associativity. So in the expression**:** `3`

`** 2 ** 2`

, `2`

raise to the power of `2`

happens first then the result (i.e., `4`

) is again raise to the power of `3`

.

Which will give `81`

as an output.

So, we can say that `3 ** 2 ** 2`

is equal to `3 ** (2 ** 2)`

.

### Non associative operators

As the name indicates, Non associative operators are those operators which do not have associativity in python.

Or, you can say, Those operators which do not follow the associativity rules of python are called non associative operators.

**Assignment operators** and **comparison operators** comes under this category.

There are specific rules for ordering of this type of operator and cannot be expressed as associativity.

**Example 1:**

Let’s say**:** `x = 5`

, `y = 4`

and `z = 3`

And, If you write a conditional expression like this**:** `x > y > z`

. Then, It neither means `(x > y) > z`

nor `x > (y > z)`

.

Rather, `x > y > z`

is equivalent to `x > y or y > z`

, and is evaluated from **left-to-right**.

**Example 2:**

Let’s say**: **`x = y = z = 1`

{Assigning a single value (**1**) to multiple variables (**x**,** y** and** z**)}.

And, If you assign a single value to multiple variables in python, then it is a valid expression.

But,

`x = y = z+= 5`

is not a valid expression. This expression will give an error.

### How do you remember operator precedence in python? (short trick)

Have you heard about **BODMAS** rule in mathematics?

I know your answer. It’s definitely gonna be YES!

BODMAS stands for **Bracket**, **Order**, **Division**, **Multiplication**, **Addition**, and** Subtraction**. This rule gives the order in which an expression can be evaluated when different arithmetic operators are encountered in an expression.

Similarly,

If you look at the above precedence table, you’ll find that the priority of operators follow the following sequence/order**:**

**–** **Parentheses****–** **Exponentiation****–** **Multiplication****–** **Division****–** **Addition****–** **Subtraction**

And, The short form of this rule is **PEMDAS** (Parentheses, Exponents, Multiplication, Division, Addition, and Subtraction), Which is the synonym of BODMAS.

A funny and short trick to remember this rule would be **“Puppy**,** Eat My Dish and Sleep”**.

### Conclusion:

So, from this article we learned**:**

**Rules of Precedence and Associativity**

**– **Precedence rules decides the order in which different operators are applied in an expression.

**– **Associativity rule decides the order in which multiple occurrences of the same level or we can say operator with same precedence are applied in an expression.

I hope this article helped you a lot.

Now, It’s your turn!

If you have any question, feel free to ask in the comment section below right now.

Awesome experience while reading this article.

Glad to hear!

You enjoyed it.