Python

How to Use Operator Module in Python

This article will cover a guide on using the “Operator” module available as a part of the default Python library. The Operator module allows you to use operator symbols programmatically using various functions. For instance, you can multiply two numbers using a function instead of using “*” symbol. The functions available in the Operator module are useful when you want to pass callable functions as arguments to another Python object. You can also serialize operator functions and store them on disk so that they can be picked again later on. Some of the functions available in the Operator module can also be used to perform quick item lookup in iterable type objects. Operator functions can also be used to replace one liner lambda functions as they provide much cleaner and shorter syntax.

Basic Syntax and Usage

The syntax of functions available in the Operator module is pretty straight forward. You call a specific function that returns a result after evaluating arguments supplied to it. Below is an example that shows mathematical calculations being done using various functions available in the Operator module.

import operator


addition = operator.add(5, 6)

subtraction = operator.sub(10, 4)

multiplication = operator.mul(3, 4)

division = operator.truediv(6, 3)


print (addition)

print (subtraction)

print (multiplication)

print (division)

The first statement imports the Operator module. Next various functions available in the Operator module like “add”, “sub”, “mul” and “truediv” are called and two numbers are supplied to them arguments so that mathematical operations can be run on them. After running the above code sample, you should get the following output:

11

6

12

2.0

The code above is equivalent to the following statements in Python:

addition = 5 + 6

subtraction = 10 - 4

multiplication = 3 * 4

division = 6 / 3


print (addition)

print (subtraction)

print (multiplication)

print (division)

In the first code sample, instead of using operator signs or symbols, you are calling functions to do the same calculations. The Operator module includes many other such utility functions. Below is an example that makes comparisons between two numbers.

import operator


equal = operator.eq(5, 6)

lessThan = operator.lt(10, 4)

lessThanEqualTo = operator.le(10, 10)

notEqual = operator.ne(6, 3)

greaterThan = operator.gt(5, 1)

greaterThanEqualTo = operator.ge(5, 6)


print (equal)

print (lessThan)

print (lessThanEqualTo)

print (notEqual)

print (greaterThan)

print (greaterThanEqualTo)

In the code sample above, various functions like “eq”, “lt”, “le”, “ne”, “gt”, and “ge” are called to determine equality or inequality of two numbers supplied as arguments to these functions. After running the above code sample, you should get the following output:

False

False

True

True

True

False

This code sample is equivalent to the following statements:

equal = 5 == 6

lessThan = 10 <4

lessThanEqualTo = 10 <= 10

notEqual = 6 != 3

greaterThan = 5 >1

greaterThanEqualTo = 5 >= 6


print (equal)

print (lessThan)

print (lessThanEqualTo)

print (notEqual)

print (greaterThan)

print (greaterThanEqualTo)

List of Useful Functions Available in the Operator Module

Below is a table showing some of the useful functions available in the Operator module and their equivalent statements. This table has been taken from official Python documentation for the Operator module.

OPERATION / CALCULATION TYPE CALLABLE FUNCTION EQUIVALENT SYNTAX
Addition add(a, b) a + b
Concatenation concat(seq1, seq2) seq1 + seq2
Containment Test contains(seq, obj) obj in seq
Division truediv(a, b) a / b
Division floordiv(a, b) a // b
Bitwise And and_(a, b) a & b
Bitwise Exclusive Or xor(a, b) a ^ b
Bitwise Inversion invert(a) ~ a
Bitwise Or or_(a, b) a | b
Exponentiation pow(a, b) a ** b
Identity is_(a, b) a is b
Identity is_not(a, b) a is not b
Indexed Assignment setitem(obj, k, v) obj[k] = v
Indexed Deletion delitem(obj, k) del obj[k]
Indexing getitem(obj, k) obj[k]
Left Shift lshift(a, b) a <<b
Modulo mod(a, b) a % b
Multiplication mul(a, b) a * b
Matrix Multiplication matmul(a, b) a @ b
Negation (Arithmetic) neg(a) – a
Negation (Logical) not_(a) not a
Positive pos(a) + a
Right Shift rshift(a, b) a >>b
Slice Assignment setitem(seq, slice(i, j), values) seq[i:j] = values
Slice Deletion delitem(seq, slice(i, j)) del seq[i:j]
Slicing getitem(seq, slice(i, j)) seq[i:j]
String Formatting mod(s, obj) s % obj
Subtraction sub(a, b) a – b
Truth Test truth(obj) obj
Ordering lt(a, b) a <b
Ordering le(a, b) a <= b
Equality eq(a, b) a == b
Difference ne(a, b) a != b
Ordering ge(a, b) a >= b
Ordering gt(a, b) a >b

You can refer to this table to find an appropriate operator function suitable for your programming requirements.

Inplace Operator Functions

The Operator module also includes a limited set of functions that can perform calculations “in-place”. This is done by modifying the object itself by passing it as an argument to an operator function. Such function names are prefixed with the “i” character. For instance, to modify an object in-place and add something to it, you will have to use “iadd” function available in the Operator module. These functions are especially useful for mutable objects like Python dictionaries and lists. Below is a code sample:

import operator


a = [1, 2, 3, 4]

operator.iadd(a, [5, 6, 7, 8])

print (a)

Here the function “iadd” has been used to concatenate two list type objects in Python. The list that will be modified in-place is supplied as the first argument, followed by the list to be joined. After running the above code sample, you should get the following output:

[1, 2, 3, 4, 5, 6, 7, 8]

Full list of in-place functions available in the Operator module can be found here.

Using Itemgetter Function

You can use the “itemgetter” function available in the Operator module to pick items from a list. Below is a basic example:

import operator


a = ["a", "b", "c", "d"]

print (operator.itemgetter(1, 2)(a))

print ((a[1], a[2]))

The itemgetter method gets an item by its index and it is especially useful for picking up multiple items in one go. The second statement shows usage of the itemgetter function where indexes of two items are supplied as arguments. The itemgetter function returns a callable object, which is then called by supplying it a Python list as an argument. The end result of the second and third statement is the same. After running the above code sample, you should get the following output:

('b', 'c')

('b', 'c')

The multiple chained calls to the itemgetter function can also be written as follows:

import operator


a = ["a", "b", "c", "d"]

b = operator.itemgetter(1, 2)

print (b(a))

The itemgetter function can also be used as a key when sorting a nested list containing other lists or tuples. Here is an example:

import operator


a = [["a", 2], ["b", 4], ["c", 1], ["d", 5]]

a.sort(key=operator.itemgetter(1))

print (a)

The “key” argument in the sort function takes a callable object. This callable object is run upon each element of the list before making any comparisons for the sorting purposes. By supplying the callable itemgetter function as the key, you are telling the sort function to pick up an item at “1” index from each nested list and use it for the comparison purposes. After running the above code sample, you should get the following output:

[['c', 1], ['a', 2], ['b', 4], ['d', 5]]

Conclusion

The Operator module doesn’t bring anything new to the table, as it uses operator symbols underneath to perform calculations. You may very well write simple statements using operator symbols. However, they are useful in scenarios where you want to programmatically perform calculations by calling up functions, pass such callable functions as arguments and replace lambda statements with something simpler.

About the author

Nitesh Kumar

I am a freelancer software developer and content writer who loves Linux, open source software and the free software community.