Search⌘ K
AI Features

Function Versions of Standard Operators

Explore how Python's operator module provides function alternatives to standard operators. Understand how these can replace lambda expressions and use partial application to create new functions. This lesson helps you write more declarative and concise functional code.

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:

 ...