Search⌘ K

Function Versions of Standard Operators

Learn when to use standard operators in Python with the help of the examples provided.

We'll cover the following...

The standard operator module contains a set of functions that are equivalent to Python operators. For example:

x = operator.add(a, b) # Equivalent to x = a + b
x = operator.truediv(a, b) # Equivalent to x = a / b
x = operator.floordiv(a, b) # Equivalent to x = a // b
Python 3.8
import operator
a=5
b=2
x = operator.add(a, b) # Equivalent to x = a + b
print(x)
x = operator.truediv(a, b) # Equivalent to x = a / b
print(x)
x = operator.floordiv(a, b) # Equivalent to x = a // b
print(x)

These are very useful functions that can often be used to replace lambda expressions. For instance, the earlier example:

 ...