Python Operators

neotam Avatar

Python Operators
Posted on :

Operators are building blocks of all kind of operation we can do in any programming language. Operators are basically the symbols which operate on at least one or more operands. Operators are surrounded by literals or variables which are called operands.

Operators and operands make up expression which is evaluated to produce the result.

For Example: If you consider the expression 9 + 3 = 10 . 9, 3 and 10 are called operands. And the symbol + is called operator.

Operator vs Operands
Operator vs Operands

There are several types of operators in python. Which are,

  1. Arithmetic Operators
  2. Comparison Operators
  3. Logical Operators
  4. Membership Operators
  5. Identity Operators
  6. Assignment Operators
  7. Bitwise Operators
  8. Compound Assignment Operators
  9. Miscellaneous Operators

Arithmetic Operators

Python arithmetic operators help to perform mathematical operation like, addition, subtraction, multiplication etc. You will find these similar across different programming languages.

+ AdditionAdds Both Operands x + y
SubtractionSubtracts right hand side operand from left hand side operandx – y
*MultiplicationMultiplies Both operands x * y
/DivisionDivides the left operand by right operand x / y
%Modulo (Remainder)Divides the left operand by right operand but returns remainderx % y
** Exponent (or) Power Operator Computes the power a ** 2
//Floor DivisionIt is like division operator /. But it returns the floored value of the result. For example 5/2 is 2.5 , but floor division results only 2.x // y
+Unary PositiveChange sign of number+a
Unary NegativeChange sign of a number to negative-a

Comparison Operators

Comparison operators are also called as relational operators.  These are building blocks of branching and decision making blocks of code you write. These  operators return Boolean True or False based on the condition satisfied or not .

Expressions that are made up of relational operators are called as conditional expression which will be evaluated to either True or False. Conditional expressions are used in conditional code written using if, elif and else constructs . 

== Equal to operator
This is operator compares the both left and right operands and return true if equal else flase
x == y
!= Not Equal to This is opposite to equal to operator. Where this operator return if both operands are not equal x != y
<> Not Equal to This is same as not equal to != . Condition becomes true only if both operands are not equal to. This operator was removed in python 3 x <> y
> Greater than The condition becomes true if left hand operand is greater than right operand x > y
< Less than The condition becomes true only if left hand operand is less than right operand x < y
>= Greater than or equal to The condition becomes true only if left hand operand is greater than or equal to the right hand operand x >= y
<= Less than or equal to The condition becomes true only if left hand operand is less than or equal to the right hand operand x <= y

Ternary Conditional Operator

This operator was introduced in Python 2.5 . Ternary Operator is used as one-liners. This operator is used in conditional assignment as well as to write if/else conditional code in one line. This is equivalent to ternary operators (? : ) supported in other languages like C/C++, Java, C# and JavaScript.

>>> n = 9
>>> "even number" if n % 2 == 0 else "odd number"
'odd number'

Notice if/else written in one line using this ternary operator

"even number" if n % 2 == 0 else "odd number"

Equivalent code of above expression written using traditional if else

if n % 2 == 0:
    print("even number")
    print("odd number")

This syntax can effectively be used in conditional assignment as follows

gender = "male"
name = "neo"
greeting = f"Hello! Mr {name}" if gender.lower() == "male" else f"Hello! Ms {name}"

Variable “greeting” was assigned conditionally based on variable gender

greeting = f"Hello! Mr {name}" if gender.lower() == "male" else f"Hello! Ms {name}"

Logical Operators 

Like any other programming languages python offers 3 logical operators. These logical operators can be applied to any literal or variable not just limited to Boolean. Like comparison operators logical operators also return either True or False. These are like conjunction words in programming languages. Logical operators help us to combine multiple conditions to write complex conditionals. These operators are not limited to use with multiple condition they can be used as short hands  or  Short Circuit Evaluations  .  If they are used in short circuiting, they return the value instead of boolean. 

andLogical ANDCondition becomes true if both operands are true(2 > x) and (2 < y)
orLogical ORCondition becomes true if at least one operand is true (2 > x) or (2 < y)
notLogical NOTIt reverses the truth value of it’s operand. Returns True if operand evaluated as False, returns False if operand Evaluated as True not x

Membership Operators 

Membership operators in python are used to check whether an element is present in the container or not. Custom Objects can implement this operator using magic method called __contains__ . This operators can be used on container data types which includes sequence and mapping data types like string,  lists and dictionaries.  It doesn’t work with scalar data types int and float. 

Returns True if Container or sequence contains given value
2 in [1, 2, 3, 4, 5]
not innot inReturns True if Container or Sequence doesn’t contain given value 2 not in [4, 9 , 34]

Identity Operators 

Identity operator compares the id(said to be address) of both operand (objects) instead of their value and return True both are same. Same id  mean both objects are same not only by their value but also by the address they are referring to object in the memory. 

isReturns True if both variables refers to the same objectx is y
is notReturns False if both variables refers to the same objectx is not y

Assignment Operator 

Assignment operator plays a vital role in programming. It is used to assign a value to the variable. 

=Assign value of right hand operand to the variable on the left handx = 2
:=Assignment expression also know as the walrus operator

Assignment Expression

Assignment expression ask walrus operator was added to python in version 3.8 . It can also be referred as “Name Expressions” . This operator is extremely useful where it is required to name intermediate results of expression or operation. Often it is required write at least couple lines, one for capturing result of an expression into a variable and then using that variable. By using assignment expression we can put both expression and assignment of evaluated value into a variable in one line. Consider following code

Regular expression match

match =
if match:

Can be written as follows using :=

if (match := is not None:

Bitwise Operators 

As the name says, bitwise operators work on bits. These operations are performed on integers of any number system, but operators perform operation on binary equivalent of given operands. 

&Bitwise ANDPerforms Binary AND operationx & y
|Bitwise ORPerforms Binary OR operationx | y
^ Bitwise XOR/ Exclusive ORPerforms Binary XOR.x ^ y
~BinaryOnes ComplementUnary Operator. Flipps the bits~x
<<Binary Left ShiftLeft hand operand value is changed by moving the number of bits to the left specified on rightx << 3
>>Binary Right ShiftLeft hand operand value is changed by moving the number of bits to the right specified on right x >> 3

Compound Assignment Operator 

If you both relational and assignment operators you get compound assignment operators. Compound assignment Operators are also called short hand operators 

+=Add and assignx += 1x = x+1
-=Subtract and Assignx -= 1x = x -1
*=Multiply and Assignx *= 1x = x * 1
/=Divide and Assignx /= 1x = x /1
%=Modulus and Assignx %= 2x = x % 2
**=Exponent and Assignx **= 2x = x ** 2
//=Floor Divide and Assignx //=2x = x // 2
&=Bitwise And and Assignx &= 2x = x & 2
|=Bitwise OR and Assignx |= 2 x = x | 2
^=Bitwise XOR and Assignx ^= 2x = x ^ 2
<<=Binary Left Shift and Assignx <<= 2x = x << 2
>>= Binary Right Shift and Assignx >> =2x = x>>2

Miscellaneous Operators 

This one included all other operators we use which don’t fall under any one of above category, These operators are

.dotThis operators is used to access attributes or methods of objectmath.sqrt(3)
()groupThese operators are used to group expression to increase it’s precedence(x + y) * z
[]subscript / indexUsed to access elements/ items of containers/sequencesx[1]
::SliceUsed on sequences to extract part of the sequencex[::]
EllipsisSpecial value used in extending slice syntax for user defined containers
@Used to implement decorators

Operator Precedence

Operator precedence describes how significant operator is in the expression, thus operator precedence dictates order in which operators are evaluated in an expression. Operands of Highest precedence operator will be evaluated first followed by next precedence operator and so on. If multiple operators have same precedence in the expression order of evaluation takes place according to the operators associativity. Most of the operators have left-to-right associativity.

Following table describes these several types of operator in python sorted according to their precedence in descending order (Highest precedence to lowest precedence)

f(args, ..)Function Call
c[index], c[index:index], f(args, ..), obj.attributeSubscription, Slicing, Function Call, Attribute Reference
await expressionAwait expression
+x, -x, ~xPositive, Negative, Bitwise NOT
*, /, //, %Multiplication, division, floor division, remainder
+, –Addition, Subtraction
<<, >>Bitwise left shift, Bitwise right shift
&Bitwise AND
^ Bitwise XOR
|Bitwise OR
in, not in, is, is not, <, <=, >, >=, !=, ==Membership tests, identity test and comparisons
not xLogical NOT
andLogical AND
orLogical OR

Expression and Evaluation

Expressions in python are made up of any combination of literals, identifiers and operators. Expressions contains operators and operands. Where operators are what we have discussed so far and operands can be literals, variables, objects, and function calls.

Every expression will break down into a single value. Where python interpreter computes the expression to produce a single final value. This process is called evaluation.

In Python evaluation of an expression happens from left to right but when it comes to assignment, right-hand side evaluated followed by left-hand side

Leave a Reply

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