ZetCode

Python operator module

last modified November 29, 2026 Python 3.15

In this article we show how to use the operator module in Python.

The operator module provides functions that correspond to the operators of Python: operator.add(a, b) does the same as a + b. Operators cannot be passed to other functions, but these functions can, so the module is useful with higher-order functions such as map, filter, sorted, and functools.reduce. It also provides the itemgetter, attrgetter, and methodcaller factories, which create small functions for key arguments and similar uses. The operators themselves are covered in the Python operators article.

Operators as functions

The arithmetic operators have functions with the same names as the special methods that implement them, without the underscores.

arithmetic.py
import operator

a = 17
b = 5

print(operator.add(a, b))
print(operator.sub(a, b))
print(operator.mul(a, b))
print(operator.truediv(a, b))
print(operator.floordiv(a, b))
print(operator.mod(a, b))
print(operator.pow(a, 2))
print(operator.neg(a))

Each call gives the same result as the operator: truediv is /, floordiv is //, mod is %, and pow is **. The unary neg function is the minus sign in front of a value.

$ python arithmetic.py
22
12
85
3.4
3
2
289
-17

Passing operators to functions

The main use of the module is to pass an operation to a function that expects a callable, instead of writing a lambda.

higher_order.py
import functools
import operator

prices = [12.5, 7.0, 3.25]
quantities = [2, 4, 10]

totals = list(map(operator.mul, prices, quantities))
print(totals)

print(functools.reduce(operator.add, totals))
print(functools.reduce(operator.mul, range(1, 7)))

words = ['an', 'old', 'falcon']
print(functools.reduce(operator.concat, words))

print(list(map(lambda x, y: x * y, prices, quantities)))

With two iterables, map calls operator.mul with a price and a quantity at a time. The functools.reduce function applies a two-argument function cumulatively: it adds the first two totals, then adds the third to the result, and so on. Multiplying the numbers 1 to 6 gives the factorial of 6, and concat joins the words. The last line does the same as the first map with a lambda; the operator version is shorter and slightly faster.

$ python higher_order.py
[25.0, 28.0, 32.5]
85.5
720
anoldfalcon
[25.0, 28.0, 32.5]

A dispatch table

Because the operator functions are ordinary objects, we can store them in a dictionary and look up an operation by its symbol.

calculator.py
import operator

operations = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.truediv,
    '//': operator.floordiv,
    '%': operator.mod,
    '**': operator.pow,
}

expressions = ['3 + 4', '10 / 4', '10 // 4', '2 ** 10', '7 % 3', '5 ^ 2']

for expression in expressions:
    left, symbol, right = expression.split()

    if symbol not in operations:
        print(f'{expression} -> unknown operator {symbol}')
        continue

    result = operations[symbol](int(left), int(right))
    print(f'{expression} = {result}')

The program evaluates simple expressions of two integers and an operator. The symbol selects the function from the dictionary, and the function is called with the two operands. An unknown symbol is reported instead of raising a KeyError. This is a common way to replace a long if/elif chain.

$ python calculator.py
3 + 4 = 7
10 / 4 = 2.5
10 // 4 = 2
2 ** 10 = 1024
7 % 3 = 1
5 ^ 2 -> unknown operator ^

Comparisons and truth tests

The comparison functions are lt, le, eq, ne, ge, and gt. The not_ and truth functions test the truth value of an object, and is_, is_not, is_none, and is_not_none test identity.

comparisons.py
import operator

print(operator.lt(3, 5))
print(operator.eq('abc', 'abc'))
print(operator.ge([1, 2], [1, 3]))

print(operator.not_([]))
print(operator.truth('falcon'))

values = [4, None, 0, '', None, 'sky']

print(list(filter(operator.is_not_none, values)))
print(list(filter(operator.truth, values)))
print(sum(map(operator.is_none, values)))

Lists are compared element by element, so [1, 2] is less than [1, 3]. An empty list is false, so not_ returns True. The is_none and is_not_none functions were added in Python 3.14. Filtering with is_not_none removes only the None values and keeps zero and the empty string, while filtering with truth removes all false values. Summing the results of is_none counts the None values, since True counts as one.

The module has no functions for the and and or keywords, because they evaluate their second operand only when needed. The and_, or_, and xor functions are the bitwise operators &, |, and ^.

$ python comparisons.py
True
True
False
True
True
[4, 0, '', 'sky']
[4, 'sky']
2

Sequence operations

Several functions work with sequences and containers: membership tests, counting, searching, concatenation, and indexing.

sequences.py
import operator

words = ['sky', 'cup', 'sky', 'war', 'sky']

print(operator.contains(words, 'cup'))
print(operator.countOf(words, 'sky'))
print(operator.indexOf(words, 'war'))
print(operator.concat([1, 2], [3, 4]))

print(operator.getitem(words, 1))
print(operator.getitem(words, slice(1, 3)))

operator.setitem(words, 0, 'sun')
operator.delitem(words, -1)
print(words)

user = {'name': 'Lucia', 'city': 'Bratislava'}
print(operator.getitem(user, 'city'))

The contains function is the in operator with the container first. The countOf and indexOf functions count occurrences and find the first position. The getitem, setitem, and delitem functions are the square bracket operations: reading, assigning, and the del statement. A slice is passed as a slice object. The same functions work with dictionary keys.

$ python sequences.py
True
3
3
[1, 2, 3, 4]
cup
['cup', 'sky']
['sun', 'cup', 'sky', 'war']
Bratislava

itemgetter

The itemgetter function creates a callable that fetches items from its argument. With one key it returns the item; with several keys it returns a tuple.

item_getter.py
import operator

point = (3, 7, 2)
user = {'name': 'Lucia', 'city': 'Bratislava', 'age': 31}

second = operator.itemgetter(1)
print(second(point))
print(second('falcon'))

name_city = operator.itemgetter('name', 'city')
print(name_city(user))

pairs = [('Peter', 23), ('Lucia', 31), ('Jozef', 19)]

print(sorted(pairs, key=operator.itemgetter(1)))
print(max(pairs, key=operator.itemgetter(1)))
print(list(map(operator.itemgetter(0), pairs)))

The second function fetches the item at index 1 of any sequence, including a string. The name_city function fetches two dictionary values at once. Passed as the key of sorted and max, itemgetter(1) compares the pairs by age. The same key could be written as lambda pair: pair[1].

$ python item_getter.py
7
a
('Lucia', 'Bratislava')
[('Jozef', 19), ('Peter', 23), ('Lucia', 31)]
('Lucia', 31)
['Peter', 'Lucia', 'Jozef']

Sorting by several fields

An itemgetter with several keys returns a tuple, and tuples are compared item by item, so it sorts by several fields at once.

sort_fields.py
import operator

employees = [
    {'name': 'Anna', 'department': 'sales', 'salary': 3200},
    {'name': 'Boris', 'department': 'it', 'salary': 4100},
    {'name': 'Clara', 'department': 'sales', 'salary': 3900},
    {'name': 'David', 'department': 'it', 'salary': 4100},
    {'name': 'Eva', 'department': 'hr', 'salary': 2900},
]

by_dept_name = sorted(employees, key=operator.itemgetter('department', 'name'))

for e in by_dept_name:
    print(e['department'], e['name'])

print()

by_salary = sorted(employees, key=operator.itemgetter('name'))
by_salary.sort(key=operator.itemgetter('salary'), reverse=True)

for e in by_salary:
    print(e['salary'], e['name'])

The first sort orders the employees by department and by name within each department. When the fields need different directions, we sort in several passes, starting with the least important field. Python's sort is stable: items with equal keys keep their order. The second listing is sorted by salary in descending order, and the two employees with the same salary stay in alphabetical order from the first pass. The Python sort list article covers sorting in detail.

$ python sort_fields.py
hr Eva
it Boris
it David
sales Anna
sales Clara

4100 Boris
4100 David
3900 Clara
3200 Anna
2900 Eva

attrgetter

The attrgetter function creates a callable that fetches attributes. A dotted name follows a chain of attributes.

attr_getter.py
import operator
from collections import namedtuple

Address = namedtuple('Address', ['city', 'country'])
Person = namedtuple('Person', ['name', 'age', 'address'])

people = [
    Person('Lucia', 31, Address('Bratislava', 'Slovakia')),
    Person('Tomas', 45, Address('Brno', 'Czechia')),
    Person('Agnes', 27, Address('Vienna', 'Austria')),
]

print(sorted(people, key=operator.attrgetter('age'))[0].name)

city = operator.attrgetter('address.city')
print(list(map(city, people)))

name_country = operator.attrgetter('name', 'address.country')

for person in sorted(people, key=operator.attrgetter('address.country')):
    print(name_country(person))

The people are named tuples with a nested address. Sorting by the age attribute finds the youngest person. The address.city name reads person.address.city. With several names, attrgetter returns a tuple, just like itemgetter. The same works for any object with attributes, such as instances of classes and data classes.

$ python attr_getter.py
Agnes
['Bratislava', 'Brno', 'Vienna']
('Agnes', 'Austria')
('Tomas', 'Czechia')
('Lucia', 'Slovakia')

methodcaller

The methodcaller function creates a callable that calls a method by name on its argument. Extra arguments are passed to the method.

method_caller.py
import operator

words = ['  Sky ', 'cup', ' Falcon', 'war  ', 'Atom']

strip = operator.methodcaller('strip')
cleaned = list(map(strip, words))
print(cleaned)

print(sorted(cleaned))
print(sorted(cleaned, key=operator.methodcaller('lower')))

lines = ['a,b,c', 'd,e', 'f']
split = operator.methodcaller('split', ',')
print(list(map(split, lines)))

pad = operator.methodcaller('rjust', 8, '.')
for word in cleaned:
    print(pad(word))

The strip function calls the strip method of each string. Sorting with methodcaller('lower') as the key ignores the case of the letters; without it, uppercase letters sort before lowercase. The split and pad functions call methods with arguments: methodcaller('rjust', 8, '.') calls word.rjust(8, '.').

$ python method_caller.py
['Sky', 'cup', 'Falcon', 'war', 'Atom']
['Atom', 'Falcon', 'Sky', 'cup', 'war']
['Atom', 'cup', 'Falcon', 'Sky', 'war']
[['a', 'b', 'c'], ['d', 'e'], ['f']]
.....Sky
.....cup
..Falcon
.....war
....Atom

In-place operators

The functions starting with i, such as iadd and imul, correspond to the augmented assignment operators like += and *=.

inplace.py
import operator

numbers = [1, 2]
result = operator.iadd(numbers, [3, 4])
print(result, numbers, result is numbers)

point = (1, 2)
result = operator.iadd(point, (3, 4))
print(result, point, result is point)

text = 'sky'
text = operator.iadd(text, 'line')
print(text)

The functions do not assign anything; they return the result, which must be assigned just like with a = a + b. A mutable list is modified in place and the same object is returned. Tuples and strings are immutable, so a new object is returned and the original stays unchanged.

$ python inplace.py
[1, 2, 3, 4] [1, 2, 3, 4] True
(1, 2, 3, 4) (1, 2) False
skyline

Calling functions

The call function, added in Python 3.11, calls its first argument with the remaining arguments: operator.call(f, x) is f(x).

dispatch.py
import operator

tasks = [
    lambda: 'tasks loaded',
    lambda: sum(range(10)),
    str.upper,
]

print(operator.call(tasks[0]))
print(operator.call(tasks[2], 'falcon'))

results = list(map(operator.call, tasks[:2]))
print(results)

The list holds two lambdas and a method of the str class. Mapping operator.call over a list of functions calls each of them, which is a compact way to run a series of callbacks and collect their results.

$ python dispatch.py
tasks loaded
FALCON
['tasks loaded', 45]

Grouping records

In the last example we combine itemgetter with itertools.groupby to summarize sales by month.

report.py
import itertools
import operator

sales = [
    ('2026-01', 'north', 120.5),
    ('2026-01', 'south', 64.0),
    ('2026-02', 'north', 33.25),
    ('2026-01', 'east', 210.0),
    ('2026-02', 'south', 99.9),
    ('2026-02', 'east', 15.75),
]

month = operator.itemgetter(0)
amount = operator.itemgetter(2)

for key, group in itertools.groupby(sorted(sales, key=month), key=month):
    rows = list(group)
    total = sum(map(amount, rows))
    best = max(rows, key=amount)
    print(f'{key}: total {total:7.2f}, best {best[1]} ({amount(best)})')

The month and amount functions name the fields of the sale tuples. The groupby function needs the records sorted by the grouping key, so we sort them first with the same key. For each month, we sum the amounts and find the best sale. The itertools groupby article explains grouping in detail.

$ python report.py
2026-01: total  394.50, best east (210.0)
2026-02: total  148.90, best south (99.9)

Source

Python operator module documentation

In this article we have used the operator module: operators as functions, dispatch tables, comparisons and truth tests, sequence operations, and the itemgetter, attrgetter, and methodcaller key functions. See also Python operators, Python lambda functions, Python map, and Python sort list.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.