Python comes with some useful standard operators for performing some basic operations. Some of these operators can be grouped as shown below:

  • arithmetic ( +, -, *, /, %, //, **)
  • comparison (==, !=, >, <, >=, <=)
  • logical (and, or, not)
  • assignment (=, +=, -=, *=, /=, %=, //=, **=)
  • membership (in, not in)
  • Bitwise(&, |, ~,  ^, <<,  >>)

The operator module in the standard library provides a functional interface for accessing and using the standard operators. This provides a convenient functionality especially in cases where we want to  pass the operator functions as arguments in other functions such as as keys in some higher order functions.

ExampleEdit & Run

Use a function from the operator module as a key function

#Get the cumulative sum of list elements 

from operator import add
from functools import reduce

data = [1, 2, 3, 4, 5]

result = reduce(add, data)
print(result)
Output:
15[Finished in 0.013112416956573725s]

Logical Operations

The module provides functions for performing logical operations for performing boolean operations. The three functions are is_(), and_ () and is_not() to match the operators is , not and is not, respectively.

Some of the functions are defined with a trailing comma to avoid conflict with the operator keywords under the same name.   

ExampleEdit & Run
#import logical functions from the module
from operator import not_, is_, is_not

#define sample variables
a = None
b = 1

#use the logical functions
print(is_(a, None))
print(not_(b))
print(is_not(a, b))
Output:
TrueFalseTrue[Finished in 0.009979552123695612s]

Arithmetic Operations

The module provides various functions to match the existing  arithmetic operators.

ExampleEdit & Run
#import some arithmetic functions
from operator import add, sub, neg, mul

a = -2
b = 4

print(neg(a)) #negate a value
print(add(a, b))
print(sub(a, b))
print(mul(a, b))
Output:
22-6-8[Finished in 0.010322152869775891s]

Comparison Operations

There is a function to match each of the rich comparison operators(<, >, <=, >=, ==, !=), ie lt(), gt(), le(), ge(), eq() and ne(), respectively.

ExampleEdit & Run
from operator import lt, le, gt, ge, eq, ne

a = 7
b = 10

for func in (lt, le, gt, ge, eq, ne):
    print(f'{func.__name__}({a}, {b}):  ', func(a, b))
Output:
lt(7, 10):   Truele(7, 10):   Truegt(7, 10):   Falsege(7, 10):   Falseeq(7, 10):   Falsene(7, 10):   True[Finished in 0.010086487047374249s]

Sequence Operations

The module also have functions for performing sequence operations such as, adding elements, searching for elements,  accessing elements and removing elements

ExampleEdit & Run
from operator import concat, contains, countOf, indexOf

seq1 = [1, 2, 3, 4]
seq2 = [5, 6, 7, 8]

print(concat(seq1, seq2))
print(contains(seq1, 3))
print(countOf(seq1, 9))
print(indexOf(seq1, 4))
Output:
[1, 2, 3, 4, 5, 6, 7, 8]True03[Finished in 0.010295149171724916s]

Operations on custom objects

User-defined classes can support the operators and the equivalent functions by defining the relevant dunder methods. This is a form of polymorphism also known as operator overloading.

ExampleEdit & Run
from operator import add, lt

class MyObj:

    def __init__(self, val):
         self.val = val

    def __str__(self):
         return 'MyObj(%s)' % self.val

    def __lt__(self, other):
         """compare for less-than"""
         return self.val < other.val
    def __add__(self, other):
         """add values"""
         return MyObj(self.val + other.val)

obj1 = MyObj(10)
obj2 = MyObj(20)

#use the objects with operator functions
print(lt(obj1, obj2))
print(obj1 + obj2)
Output:
TrueMyObj(30)[Finished in 0.009921562857925892s]

In the above example, we created a custom class with a name Myobj, we defined the __lt__() and  __add__() dunder methods so that objects of the class will support the less than and  addition operations respectively.  We then created two objects of the class and then performed the two operations on them. 

All the available functions 

The functions provided in the module are as summarized below:

Function

Usage

Similar to

abs

abs(a)

abs(a)

add

add(a,b)

a+b

and_

and_(a,b)

a&b

concat

concat(a,b)

a+b

contains

contains(a,b)

b in a

countOf

countOf(a,b)

a.count(b)

delitem

delitem(a,b)

del a[b]

delslice

delslice(a,b,c)

del a[b:c]

div

div(a,b)

a/b

eq

eq(a,b)

a==b

floordiv

floordiv(a,b)

a//b

ge

ge(a,b)

a>=b

getitem

getitem(a,b)

a[b]

getslice

getslice(a,b,c)

a[b:c]

gt

gt(a,b)

a>b

indexOf

indexOf(a,b)

a.index(b)

invert, inv

invert(a)inv(a)

~a

is

is(a,b)

a is b

is_not

is_not(a,b)

a is not b

le

le(a,b)

a<=b

lshift

lshift(a,b)

a<<b

lt

lt(a,b)

a<b

mod

mod(a,b)

a%b

mul

mul(a,b)

a*b

ne

ne(a,b)

a!=b

neg

neg(a)

-a

not_

not_(a)

not a

or_

or_(a,b)

a|b

pos

pos(a)

+a

repeat

repeat(a,b)

a*b

rshift

rshift(a,b)

a>>b

setitem

setitem(a,b,c)

a[b]=c

setslice

setslice(a,b,c,d)

a[b:c]=d

sub

sub(a,b)

a-b

truediv

truediv(a,b)

a/b # "true" div -> no truncation

truth

truth(a)

not a, bool(a)

xor_

xor(a,b)

a^b