operator

The Python operator module provides functions that correspond to the Python operators. This module allows you to use operators as functions, which can be especially useful when combined with higher-order functions, such as map(), filter(), and reduce().

Here’s a quick example:

Python
>>> import operator
>>> operator.add(1, 2)
3

Key Features

  • Provides function equivalents for standard Python operators
  • Supports Boolean, mathematical, comparison, identity, membership, and bitwise operations
  • Offers item and attribute getter functions for convenience

Frequently Used Classes and Functions

Object Type Description
operator.add() Function Adds two numbers
operator.sub() Function Subtracts the second number from the first
operator.itemgetter() Function Returns a callable that fetches an item from its operand
operator.attrgetter() Function Returns a callable that fetches an attribute from its operand
operator.methodcaller() Function Returns a callable that calls a method on its operand

Examples

Using the operator.sub() function:

Python
>>> import operator
>>> operator.sub(4, 5)
-1

Using operator.itemgetter() to extract elements by index:

Python
>>> data = [(2, "b"), (1, "a"), (3, "c")]
>>> sorted(data, key=operator.itemgetter(1))
[(1, 'a'), (2, 'b'), (3, 'c')]

Common Use Cases

  • Replacing lambda functions with more readable operator functions
  • Using itemgetter() and attrgetter() for sorting and key extraction
  • Performing functional programming operations in a concise manner

Real-World Example

Suppose you have a list of tuples representing students’ grades, and you want to sort them by their scores:

Python
>>> import operator
>>> students = [("John", 88), ("Jane", 92), ("Dave", 85)]
>>> sorted(students, key=operator.itemgetter(1), reverse=True)
[('Jane', 92), ('John', 88), ('Dave', 85)]

In this example, you use operator.itemgetter() to sort a list of tuples by the second element, providing a clear and efficient solution.

Tutorial

Working With the Python operator Module

In this tutorial, you'll explore the Python operator module and its role in functional programming. You'll code several examples of using both operator-equivalent and higher-order functions in programs.

intermediate data-structures python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated July 16, 2025