Precedence Of Operator's in Python

Vijaya Kumar Chinthala
2 min readMar 1, 2021

When an expression or statement involves multiple operators, python resolves the order of execution through Operator Precedence.

Here We will see the list of highest precedence to lowest of all the operators in python.

Example 1:

>>> 2**3*2
16
>>> 2**(3*2)
64
  1. In the above code in the first statement as **(exponentiation) is executed first as it has highest precedence than *(Multiplication)
  2. Next statement ( ) has highest precedence than remaining hence it is executed first.

Example 2:

>>> ~3+1
-3
>>> ~(3+1)
-5
  1. In the first statement ~ (Bitwise not) is executed first
  2. Second statement ( ) is executed first, 3+1 is performed first and later bitwise not applied to 4.

Example 3:

>>> 100*2/5//2%3
2.0
  1. If all the operators have equal precedence then it executes from left to right. In the above statement first 100*2 calculated 200.
  2. Later it is divided by 5 which is equal to 40.0
  3. Later floor division done on 40.0 with 2 which is equal to 20.0
  4. Later Modulo is applied between 20.0 % 3 which is equal to 2.

Example 4:

>>> 20+3*4
32
>>> 20-3*4
8
  1. In the first statement *(Multiply) has high precedence than +(Addition) hence 3*4 calculated first.

Example 6:

>>> 0|1&1^1
0
>>> 0|1&0^1
1
  1. In the first statement 1&1 is calculated which is 1, Later 1|1 calculated which is 0, Later 0|0 calculated which is 0.
  2. In the second statement 1&0 calculated which is 0,Later 0(Bitwise XOR) 1 calculated which is 1,Later 0|1 calculated which is 1.

Example 7:

>>> not 7>8 and 6<8 or 1!=2
True
  1. not 7>8 and 6<8 or 1!=2==>not False and True or True
  2. not False and True or True==>True and True or True
  3. True and True or True==>True or True
  4. True or True==>True

Example 8:

>>> 2 in [1,2,3,4] and True or not False
True
  1. 2 in [1,2,3,4] and True or not False==> True and True or not False
  2. True and True or not False==>True and True or True
  3. True and True or True==>True or True
  4. True or True==> True
>>> 5 in [1,2,3,4] and True or not True
False
  1. 5 in [1,2,3,4] and True or not True==> False and True or not True
  2. False and True or not True==>False and True or False
  3. False and True or False==>False or False
  4. False or False==> False

--

--