Operator precedence in python with examples


The following table lists all operators from highest precedence to lowest.

OperatorDescription
** Exponentiation (raise to the power)
~ + - Complement, unary plus and minus (method names for the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'td>
^ | Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators

Operator precedence affects how an expression is evaluated.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first multiplies 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom.

Example

#!/usr/bin/python

a = 20
b = 10
c = 15
d = 5
e = 0

e = (a + b) * c / d       #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ",  e

e = ((a + b) * c) / d     # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ",  e

e = (a + b) * (c / d);    # (30) * (15/5)
print "Value of (a + b) * (c / d) is ",  e

e = a + (b * c) / d;      #  20 + (150/5)
print "Value of a + (b * c) / d is ",  e

When you execute the above program, it produces the following result −

Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50

python_basic_operators.htm

Operator precedence in python with examples
Onyejiaku Theophilus Chidalu

Overview

Operator precedence in Python simply refers to the order of operations. Operators are used to perform operations on variables and values.

Python classifies its operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical/Bitwise operators
  • Identity operators
  • Membership operators

Arithmetic Operators

Common arithmetic operators in Python include:

  • Addition +
  • Subtraction -
  • Multiplication *
  • Division/modulus /or//
  • Exponentiation **
  • Brackets/Parenthesis ()

Order of operations

The order of operations of the arithmetic operators can be remembered using the acronym BEDMAS.

The acronym stands for the following words, which tell us which operator comes first:

  • B= Bracket
  • E = Exponentiation
  • D = Division
  • M = Multiplication
  • A = Addition
  • S = Subtraction

Through the acronym, we can see that the bracket/parenthesis operator comes before the exponentiation operation in Python, according to the order of operations.

The same logic applies to each of the following operators, down to the subtraction operator.

Example

To fully grasp BEDMAS and the order of preference of the operators, let’s take a look at the example below:

X = (5 + 3) * 2 ** 2
print(X)

From this program, we can see that there are three operators:

  • Bracket (B)
  • Exponentiation (E)
  • Multiplication (M)

According to operator precedence, Python first deals with the numbers in the bracket operator (B): (5 + 3) = 8.

We then proceed to the exponentiation operator (E): 2 ** 2 = 4.

Finally, the results of both the bracket (8) and exponentiation (4) operators are then executed using the multiplication operator (M): 8 * 4 = 32.

In short, Python followed the order of operators outlined in BEDMAS.

Example

The same logic applies to the examples below:

x = 3 + 8 * 2** 3
print(x)
y= (4 * 2) + 6 / 3 - 2
print(y)

The value of x in the example above follows E,M,A order of operations while the value of y follows B,D,S order.

Assignment Operators

Common assignment operators in Python include:

  • Assign operator =
  • Add AND operator+=
  • Subtract AND operator -=
  • Multiply AND operator *=
  • Divide AND operator /=
  • Modulo AND operator %=
  • Exponent AND operator **=

Order of operation

Since these operators are not associative, there is no order of operation for them. They are always performed or declared exclusively.

Example

# using the assigm operator 
x = 6
y = 2 
# to generate the Add AND operator i.e  x + y = 8
x += y
print(x) 
# to generate the subtract AND operator i.e x - y = 8 - 2 = 6  
x -= y 
print(x)
# to generate the multiply AND ooperator i.e x * y = 6 * 2 = 12
x *= y 
print(x)
# to generate the divide AND operator i.e x / 2 = 12 / 2 = 6  
x /= y 
print(x)
# to generate the modulo AND operator 1.e x %= 2 = 6 % 2 = 0
x %= y
print(x)

Comparison Operators

Comparison operators include:

  • Equal to ==
  • Not equal to !=
  • Greater than >
  • Less than <
  • Greater than or equal to >=
  • Less than or equal to <=

Order of operation

Since these operators are not associative, there is no order of operation for them. They are always performed or declared exclusively.

Example

The program below introduces each of the comparison operators:

x = 6
y = 2
if x == y:
    print('x is equal to y')
else:
    print('x is not equal to y')
if x != y:
    print('x is not equal to y')
else:
    print('x is equal to y')
if x > y:
    print('x is greater than y')
else:
    print('x is not greater thab y')
if x < y:
    print('x is less than y')
else:
    print('x is not less than y')
if x >= y:
    print('x is greater than or equal to y')
else:
    print('x is not greater than or equal to y')
if x <= y: 
    print('x is less than or equal to y')
else:
    print('x is not less than or equal to y')

Logical operators

Logical operators in Python include:

  • Logical AND
  • Logical OR
  • Logical NOT

Order of operations

The order of operations for logical operators from the highest to the lowest is as follows:

  1. NOT
  2. AND
  3. OR

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

The example above shows how the precedence of the logical and is greater than the logical or.

Identity operators

The identity operators in Python include:

  • Is
  • Is not

The order of precedence of the identity operators in Python from left to right would be: is and is not.

Membership operators

The order of precedence of the membership operators in Python from left to right is in, not in.

Example

In the code below, we check whether or not the values of x = 2 and y = 4 are available in list by using in and not in operators.

x = 2
y = 4
list = [1, 2, 3, 6, 7 ];
if ( x in list ):
   print("Yes x is in the list")
else:
   print("x can not be found on the list")
if ( y not in list ):
   print("y is not in the given list")
else:
   print("y is in the  given list")

The example above shows how the precedence of in is greater than the not in.

Summary

The table below shows the summary of the different operator and their precedencies in python

OperatorsExamplesOperator Precedence(from left to right)
Arithmetic operators Addition+, Subtraction-, Multiplication *, Division/modulo/or//,Exponential **, Bracket() (),**, /or//,*, +,-
Assignment operators Assign operator =, Add AND operator+=, Subtract AND operator -=, Multiply AND operator *=, Divide AND operator /=, Modulo AND operator %=, Exponent AND operator **= No order of operation
Comparison operators equal to ==, not equal to !=, greater than >, less than <, greater than or equal to >=, less than or equal to <= No order of operation
Logical operators Logical AND, Logical OR, Logical NOT NOT, AND, OR
Identity operators Is, Is not Is, Is not
Membership operators in, not in in, not in

CONTRIBUTOR

Operator precedence in python with examples
Onyejiaku Theophilus Chidalu

What is operator precedence explain with example?

The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3 , the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary.

What is the order of precedence of operators in Python?

Python follows the same precedence rules for its mathematical operators that mathematics does. Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8.

What is meant by operator precedence and associativity in Python?

Operator Associativity: 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.