Open In App

Precedence and Associativity of Operators in Python

Last Updated : 01 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, operators have different levels of precedence, which determine the order in which they are evaluated. When multiple operators are present in an expression, the ones with higher precedence are evaluated first. In the case of operators with the same precedence, their associativity comes into play, determining the order of evaluation.

Operator Precedence and Associativity in Python

Please see the following precedence and associativity table for reference. This table lists all operators from the highest precedence to the lowest precedence.

Precedence Operators Description Associativity

1

()

Parentheses

Left to right

2

x[index], x[index:index]

Subscription, slicing

Left to right

3

await x

Await expression

N/A

4

**

Exponentiation

Right to left

5

+x, -x, ~x

Positive, negative, bitwise NOT

Right to left

6

*, @, /, //, %

Multiplication, matrix, division, floor division, remainder

Left to right

7

+,

Addition and subtraction

Left to right

8

<<, >>

Shifts

Left to right

9

&

Bitwise AND

Left to right

10

^

Bitwise XOR

Left to right

11

|

Bitwise OR

Left to right

12

in, not in, is, is not, <, <=, >, >=, !=, ==

Comparisons, membership tests, identity tests

Left to Right

13

not x

Boolean NOT

Right to left

14

and

Boolean AND

Left to right

15

or

Boolean OR

Left to right

16

if-else

Conditional expression

Right to left

17

lambda

Lambda expression

N/A

18

:=

Assignment expression (walrus operator)

Right to left

Precedence of Python Operators

This is used in an expression with more than one operator with different precedence to determine which operation to perform first.

Example

10 + 20 * 30

Precedence Python

10 + 20 * 30 is calculated as 10 + (20 * 30)
and not as (10 + 20) * 30

Python Code of the above Example

Python3




# Precedence of '+' & '*'
expr = 10 + 20 * 30
 
print(expr)


Output

610

Precedence of Logical Operators in Python

In the given code, the ‘if‘ block is executed even if the age is 0. Because the precedence of logical ‘and‘ is greater than the logical ‘or‘.

Python3




# Precedence of 'or' & 'and'
name = "Alex"
age = 0
 
if name == "Alex" or name == "John" and age >= 2:
    print("Hello! Welcome.")
else:
    print("Good Bye!!")


Output

Hello! Welcome.

Hence, To run the ‘else‘ block we can use parenthesis( ) as their precedence is highest among all the operators.

Python3




# Precedence of 'or' & 'and'
name = "Alex"
age = 0
 
if (name == "Alex" or name == "John") and age >= 2:
    print("Hello! Welcome.")
else:
    print("Good Bye!!")


Output

Good Bye!!

Associativity of Python Operators

If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.

Example

In this code, ‘*’ and ‘/’ have the same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.

Associativity Python

Code

Python3




# Left-right associativity
# 100 / 10 * 10 is calculated as
# (100 / 10) * 10 and not
# as 100 / (10 * 10)
print(100 / 10 * 10)
 
# Left-right associativity
# 5 - 2 + 3 is calculated as
# (5 - 2) + 3 and not
# as 5 - (2 + 3)
print(5 - 2 + 3)
 
# left-right associativity
print(5 - (2 + 3))
 
# right-left associativity
# 2 ** 3 ** 2 is calculated as
# 2 ** (3 ** 2) and not
# as (2 ** 3) ** 2
print(2 ** 3 ** 2)


Output

100
6
0
512

Operators Precedence and Associativity in Python

Operators Precedence and Associativity are two main characteristics of operators that determine the evaluation order of sub-expressions in the absence of brackets.

Example

100 + 200 / 10 - 3 * 10

Precedence and Associativity Python

100 + 200 / 10 - 3 * 10 is calculated as 100 + (200 / 10) - (3 * 10)
and not as (100 + 200) / (10 - 3) * 10

Python Code of the above Example

Python3




expression = 100 + 200 / 10 - 3 * 10
print(expression)


Output

90.0

Non-associative Operators

In Python, most operators have associativity, which means they are evaluated from left to right or right to left when they have the same precedence. However, there are a few operators that are non-associative, meaning they cannot be chained together.

Example

Python3




a = 5
b = 10
c = 15
 
a = b = (a < b) += (b < c)


Output

a = b= (a < b) += (b < c)
^^
SyntaxError: invalid syntax


Previous Article
Next Article

Similar Reads

Operators Precedence in Scala
An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Which operator is performed first in an expression with more than one operators with different precedence is determined by operator precedence. For example, 10 + 20 * 30 is calculated as 10 + (20 *
3 min read
Python | Solve given list containing numbers and arithmetic operators
Given a list containing numbers and arithmetic operators, the task is to solve the list. Example: Input: lst = [2, '+', 22, '+', 55, '+', 4] Output: 83 Input: lst = [12, '+', 8, '-', 5] Output: 15 Below are some ways to achieve the above tasks. Method #1: Using Iteration We can use iteration as the simplest approach to solve the list with importing
3 min read
Merging and Updating Dictionary Operators in Python 3.9
Python 3.9 is still in development and scheduled to be released in October this year. On Feb 26, alpha 4 versions have been released by the development team. One of the latest features in Python 3.9 is the merge and update operators. There are various ways in which Dictionaries can be merged by the use of various functions and constructors in Pytho
3 min read
Python Operators for Sets and Dictionaries
Following article mainly discusses operators used in Sets and Dictionaries. Operators help to combine the existing value to larger syntactic expressions by using various keywords and symbols. Sets: Set class is used to represent the collection of elements without duplicates, and without any inherent order to those elements. It is enclosed by the {}
6 min read
Increment += and Decrement -= Assignment Operators in Python
If you're familiar with Python, you would have known Increment and Decrement operators ( both pre and post) are not allowed in it. Python is designed to be consistent and readable. One common error by a novice programmer in languages with ++ and -- operators are mixing up the differences (both in precedence and in return value) between pre and post
3 min read
Python Membership and Identity Operators
There is a large set of Python operators that can be used on different datatypes. Sometimes we need to know if a value belongs to a particular set. This can be done by using the Membership and Identity Operators. In this article, we will learn about Python Membership and Identity Operators. Table of Content Python Membership OperatorsPython IN Oper
7 min read
Division Operators in Python
Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. Division Operators in PythonThere are two types of division operators: Float divisionInteger division( Floor division)When an integer is divided, the
5 min read
Python | Operators | Question 1
What is the output of the following code : C/C++ Code print 9//2 (A) 4.5 (B) 4.0 (C) 4 (D) Error Answer: (C)Explanation: The ‘//’ operator in Python returns the integer part of the floating number. Quiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Operators | Question 2
Which function overloads the &gt;&gt; operator? (A) more() (B) gt() (C) ge() (D) None of the above Answer: (D) Explanation: rshift() overloads the &gt;&gt; operatorQuiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Operators | Question 3
Which operator is overloaded by the or() function? (A) || (B) | (C) // (D) / Answer: (B) Explanation: or() function overloads the bitwise OR operatorQuiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Practice Tags :