Python Operator Precedence – Learn how to perform operations in Python
There are many different types of operators. 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.
Operator | Description |
:= | Assignment expression (Lowest precedence) |
lambda | Lambda expression |
if-else | Conditional expression |
or | Boolean OR |
and | Boolean AND |
not x | Boolean 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, ~x | Unary plus, Unary minus, bitwise NOT |
** | Exponentiation |
await x | Await expression |
x[index], x[index:index], x(arguments…), x.attribute | Subscription, slicing, call, attribute reference |
(expressions…), [expressions…],
{key: value…}, {expressions…} |
Binding or parenthesized expression, list display, dictionary display, set display |
() | Parentheses (Highest precedence) |
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.
5 - 2
Output:
5-2 is an expression that contains a single operator.
However, an expression can also contain multiple operators and operands.
10-5/5
Output:
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:
(10-5)/5
Output:
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”.
Now we apply the PEMDAS rule and evaluate the following expression –
((((6+4)*2)-10)//2)-4*2
Output:
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.
This means that in an expression with multiple associative operators of the same precedence, the operations are performed sequentially from left to right, ensuring consistent and predictable results.
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.
45 % 10 / 2
Output:
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.
45% (10/2)
Output:
Here, we forced the expression to evaluate from right to left.
Example 2:
The exponentiation operator evaluates from right to left.
2**2**3
Output:
If we want to see the output of left to right, we can use parentheses.
(2**2)**3
Output:
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. This ensures logical evaluation without ambiguity.
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.
0 or “Hey” and 1
Output:
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.
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
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”.
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
True
3. Short-circuiting with conditional operators
Conditional operators also follow short-circuiting. Let’s see it with an example.
def check(i) "Watch how this unfurls with conditional operators like > and <. Have a look at Python Bitwise Operator" return i print(5>20>check(50))
Output:
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.