operator | Python Standard Library – Real Python

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:

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

Examples

Using the operator.sub() function:

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

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:

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

Working With the Python operator Module

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