Skip to content

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:

Language: 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
  • Includes the is_none() and is_not_none() identity helpers, added in Python 3.14
  • 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:

Language: Python
>>> import operator

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

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

Language: Python
>>> import operator

>>> 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:

Language: 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.

Operators and Expressions in Python

Tutorial

Operators and Expressions in Python

In Python, operators are special symbols, combinations of symbols, or keywords that designate some type of computation. You can combine objects and operators to build expressions that perform the actual computation. So, operators are the building blocks of expressions.

basics python

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

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Oct. 15, 2026