Python Operator Precedence – Learn how to perform operations in Python

As we have seen in earlier tutorials that there are many different types of operators and when evaluating complex expressions like 5+2*4%6-1 and 13 or 3 one might easily get confused about in which order the operations will be performed. This Python operator precedence article will help you in understanding how these expressions are evaluated and the order of precedence Python follows.

Python Operators Precedence Table

Here we have a table that is arranged in the ascending order of precedence of operators. The new Assignment expression (:=) operator from Python 3.8 onwards has the lowest precedence while parentheses() have the highest precedence.

OperatorDescription
:=Assignment expression (Lowest precedence) 
lambdaLambda expression
if-elseConditional expression
orBoolean OR
andBoolean AND
not xBoolean NOT
<, <=, >, >=Comparison operators
!=, ==Equality operators
in, not in, is, is not,Identity operators, membership operators
|Bitwise OR
^Bitwise XOR
&Bitwise AND
<<, >>Left and right Shifts
+, Addition and subtraction
*, @, /, //, %Multiplication, matrix multiplication, division, floor division, remainder
+x, -x, ~xUnary plus, Unary minus, bitwise NOT
**Exponentiation
await xAwait expression
x[index], x[index:index], x(arguments…), x.attributeSubscription, slicing, call, attribute reference
(expressions…),

[expressions…], {key: value…}, {expressions…}

Binding or parenthesized expression, list display, dictionary display, set display
()Parentheses (Highest precedence) 

Get ready to clear your Python Operator concepts with TechVidvan.

What are Expressions in Python?

Before we move further, let’s first understand what are expressions.

An expression is made with combinations of variables, values, operators and function calls. The Python interpreter evaluates the valid expression. Have a look at a very simple expression.

Code:

5 - 2

Output:

3

5-2 is an expression that contains a single operator. However, an expression can also contain multiple operators and operands.

Code:

10-5/5

Output:

9.0

In this expression, it first divided the 5/5 and then subtracted the result from 10 because, in Python, the division operator has higher precedence than subtraction.

Let’s look at this example:

Code:

(10-5)/5

Output:

1.0

Here, with the use of parentheses, we force the interpreter to first evaluate the expression inside the parentheses and then continue the overall evaluation.

Python Operators Precedence Rule – PEMDAS

You might have heard about the BODMAS rule in your school’s mathematics class. Python also uses a similar type of rule known as PEMDAS.

P – Parentheses
E – Exponentiation
M – Multiplication
D – Division
A – Addition
S – Subtraction

The precedence of operators is listed from High to low. To remember the abbreviations, we have a funny mnemonic “Please Excuse My Dear Aunt Sally”.python operator precedence

Now we apply the PEMDAS rule and evaluate the following expression –

Code:

((((6+4)*2)-10)//2)-4*2

Output:

-3.0

How did we get -3? Let’s break down the evaluation:

(6+4) = 10
(10*2) = 20
(20-10) = 10
(10//2) = 5
4*2 = 8
5-8 = -3

Associativity of Operators in Python

If you observed the precedence table, you may have noticed that many cells had more than one operator which means that they have the same precedence. So then, which will be evaluated first is managed by the associativity of operators.

1. Associative Operators

The associative operators are division, multiplication, remainder, etc and the expressions will be evaluated from left to right.

Almost all operators except the exponentiation(**) operator support left-to-right associativity.

Example 1:

Suppose modulus(%) and division(/) operators have the same precedence. So, if both operators are present in an expression, then the left one is evaluated first.

Code:

45 % 10 / 2

Output:

2.5

First, 45%10 gives 5 and then 5/2 gives us 2.5 as output. If this was evaluated from right to left, we would get a different output.

Code:

45% (10/2)

Output:

0.0

Here, we forced the expression to evaluate from right to left.

Example 2:

The exponentiation operator evaluates from right to left.

Code:

2**2**3

Output:

256

If we want to see the output of left to right, we can use parentheses.

Code:

(2**2)**3

Output:

64

Time to Level up your coding skills using Python Bitwise operators.

2. Non-Associative Operators

The comparison operator and the assignment operators do not support associativity which means that an expression like 10<20<30 doesn’t mean (10<20)<30 or 10<(20<30 ). They both mean the same thing as they are evaluated from left to right.

The statement 10<20<30 means 10<20 and 20<30.

You can also chain the assignment operators in any order and they will behave the same way.

a = b = c = d will be same as b = a = d = c or d = c = b = a.

Short-Circuiting in Python Operators Precedence

As we saw how Python mostly evaluates the expression from left-to-right. In expression with ‘and’, ‘or’ operators, Python uses Short-Circuiting which means that it will evaluate the right side only when it is needed. You’ll understand this better with examples.

1. Short-circuiting with and/or

The boolean operation will stop executing when we arrive at the truth value of the expression.

  • x or y: Evaluates y only when x is false.
  • x and y: Evaluates y only when x is true.

Code:

0 or “Hey” and 1

Output: 

1

0 or “Hey” returns “Hey”
“Hey” and 1 returns 1

2. Short-circuiting with all()/ any()

The inbuilt functions all() and any() also supports short-circuiting.

  • all() function checks that all statements should be ‘True’. So when the first ‘False’ statement occurs, it stops further executing and returns False.

Code:

def short_ciruit(i):
  print(“Executing”)
  return i

print(all(short_circuit(i) for i in [1,2,3,0,5,6] ) )

Output:

Executing
Executing
Executing
Executing
False
  • any() function returns “True” if one of the statements is true. So, when the first ‘True’ statement occurs, we don’t need to execute any further and simply return “True”.

Code:

def short_ciruit(i):
  print(“Executing”)
  return i

print(any(short_circuit(i) for i in [0,0,3,0,5,6] ) )

Output:

Executing
Executing
Executing
True

3. Short-circuiting with conditional operators

Conditional operators also follow short-circuiting. Let’s see it with an example.

Code:

  def check(iWatch how this unfurls with conditional operators like > and <.
Have a look at Python Bitwise Operator)
    return i

  print(5>20>check(50))

Output:

False

The statement stopped executing when the statement becomes false and it was no longer needed to execute it further so the check(50) method didn’t run.

Summary

In this article, we studied the important topic of Python operators precedence table. We understood the rules of operator precedence and how Python evaluates complex expressions.

Some operators are associative while some are non-associative. Later on, we saw more on short-circuiting that Python stops executing when it is sure of the result and thus it doesn’t need to execute code any further.

Now is the time to learn how to compare values using Python comparison operators.

In case you have any doubts in our Python operator precedence article, feel free to leave a comment.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.