Faster Sorting Without Lambdas? Python's operator Module

This article explains how Python's operator module replaces small lambdas with itemgetter, attrgetter, methodcaller and arithmetic functions, measures how much faster they make sorting, and describes their pitfalls.

A green tree python coiled around a branch among dark leaves, with its mouth open.
Photo by Robin McSkelly on Unsplash

Sorting a list of records by one of its fields is usually written with a small lambda, such as key=lambda row: row["age"], and the same pattern reappears in min, max, groupby and map. The present article addresses the module operator, which provides ready-made callables for these accessors and for the operators of the language: itemgetter reads keys or indexes, attrgetter reads attributes, methodcaller calls a method, and functions such as add and mul stand for the arithmetic operators. Their speed is measured instead of assumed, and their limits are described, because a getter cannot express everything that a lambda can. Naming the field instead of writing a function that reads it, in a form that is faster to call and can be pickled, is the secret weapon of the module operator.

Getters for Keys, Attributes and Methods

The three getters build a callable from the name of what must be read. itemgetter uses the operand's __getitem__, so it serves dictionaries, lists and tuples; attrgetter reads attributes and accepts dotted names for nested objects; methodcaller calls a method with fixed arguments. When several items or attributes are requested, the result is a tuple, which is exactly the shape that a multi-key sort requires. The following example applies the three getters to records and objects.

from operator import attrgetter, itemgetter, methodcaller
from types import SimpleNamespace

users = [
    {"name": "Lia", "age": 30},
    {"name": "Bob", "age": 25},
    {"name": "Ana", "age": 30},
]
print([u["name"] for u in sorted(users, key=itemgetter("age"))])
# Output: ['Bob', 'Lia', 'Ana']
print([u["name"] for u in sorted(users, key=itemgetter("age", "name"))])
# Output: ['Bob', 'Ana', 'Lia']

author = SimpleNamespace(name=SimpleNamespace(first="Ada", last="Lovelace"))
print(attrgetter("name.first", "name.last")(author))  # Output: ('Ada', 'Lovelace')

words = ["banana", "Apple", "cherry"]
print(sorted(words, key=methodcaller("lower")))  # Output: ['Apple', 'banana', 'cherry']
print(methodcaller("split", ",")("a,b,c"))       # Output: ['a', 'b', 'c']

The first sort keeps Lia before Ana because both have the same age and the sort is stable, whereas the second one breaks the tie with the name, since the getter returns the tuple (age, name). For a method without arguments, the unbound method str.lower is equivalent to methodcaller("lower"), and methodcaller becomes necessary only when arguments must be fixed or when the type of the operand is not known in advance.

Speedrun Timing: How Much Time a Getter Actually Saves

Speedrunners compare split times segment by segment, because a faster segment saves only the time that the segment itself takes. This means that the speed of a key function must be compared with the whole operation in which it runs, not in isolation. On CPython 3.12, with 100,000 dictionaries, extracting the key with itemgetter took about 1.6 milliseconds against 3.2 for the equivalent lambda, so the getter halves the extraction cost. The complete sorted call, however, took about 8.8 milliseconds against 10.5, a gain of roughly 15 percent, because a sort calls the key function only once per element and spends most of its time comparing the keys. The analogy, however, stops at this point, because a key function is not a segment that runs once: it is called for every element, so its cost grows with the data, while the comparisons grow faster still.

The same reasoning applies outside sorting. The arithmetic functions of the module replace small lambdas in map and functools.reduce, and getters can be pickled, which matters when a key function is sent to another process. The following example shows both properties and builds a sort with mixed directions from two stable passes.

import operator
import pickle
from functools import reduce
from operator import itemgetter

print(list(map(operator.mul, [1, 2, 3], [4, 5, 6])))  # Output: [4, 10, 18]
print(reduce(operator.add, [1, 2, 3, 4]))             # Output: 10

restored = pickle.loads(pickle.dumps(itemgetter("age")))
print(restored)  # Output: operator.itemgetter('age')
try:
    pickle.dumps(lambda row: row["age"])
except pickle.PicklingError:
    print("a lambda cannot be pickled")  # Output: a lambda cannot be pickled

rows = [("ana", 30), ("bob", 25), ("cy", 30), ("al", 25)]
rows.sort(key=itemgetter(0))                 # secondary key, ascending
rows.sort(key=itemgetter(1), reverse=True)   # primary key, descending
print(rows)  # Output: [('ana', 30), ('cy', 30), ('al', 25), ('bob', 25)]

A getter carries its own description, which is why it survives pickle and prints a readable repr, whereas a lambda defined inside a function has no importable name. Pickling partial applications follows the same rule, as examined in the article devoted to functools.partial. The two-pass sort works because a stable sort preserves the order of equal elements, so the names remain ascending within each age. For sums, the built-in sum remains preferable: on 1,000 integers it took about 3.9 microseconds, against 17.5 for reduce(operator.add, ...) and 36 for reduce with a lambda. Python 3.14 adds operator.is_none and operator.is_not_none, which allow filter(operator.is_not_none, values) without a lambda.

Pitfalls of the operator Module

A getter is a fixed accessor, so its pitfalls appear when the data are irregular or when the key needs logic that the getter cannot express. Six pitfalls are distinguished, which are the following:

  1. Scalar or tuple. itemgetter(*fields) returns a single value when fields has one element and a tuple otherwise, which breaks code that always expects a tuple.
  2. Missing fields. A getter raises KeyError or AttributeError for a missing key or attribute and has no default, so irregular records need a lambda with dict.get.
  3. Incomparable keys. A None among integers raises TypeError during the sort, and the getter cannot replace it.
  4. Mixed directions. A single getter sorts every field in the same direction; descending and ascending fields require successive stable sorts.
  5. Overestimated speed. The getter reduces the cost of extracting the key, not the cost of comparing keys, so the gain in a full sort is modest.
  6. In-place functions on immutable values. operator.iadd on a tuple returns a new tuple and does not rebind the variable, unlike the statement +=.

The first, third and sixth pitfalls, together with a measurement of key extraction alone, are reproduced in the following example.

import operator
import timeit
from operator import itemgetter

fields = ["age"]
print(itemgetter(*fields)({"age": 30}))          # Output: 30
print(itemgetter("age", "name")({"age": 30, "name": "Ana"}))  # Output: (30, 'Ana')

try:
    sorted([{"age": 30}, {"age": None}], key=itemgetter("age"))
except TypeError as error:
    print(error)  # Output: '<' not supported between instances of 'NoneType' and 'int'

point = (1, 2)
print(operator.iadd(point, (3,)), point)  # Output: (1, 2, 3) (1, 2)

rows = [{"age": i % 90} for i in range(100_000)]
by_lambda = lambda row: row["age"]
by_getter = itemgetter("age")
t_lambda = min(timeit.repeat(lambda: list(map(by_lambda, rows)), number=20, repeat=5))
t_getter = min(timeit.repeat(lambda: list(map(by_getter, rows)), number=20, repeat=5))
print(t_lambda > 1.3 * t_getter)  # Output: True

The measurement takes a few seconds, because it maps 100,000 records twenty times per repetition. It confirms that extracting the key is faster with the getter, while the earlier figures show that this advantage is diluted in a complete sort.

Choosing an Accessor

Consequently, a getter suits keys that read a field directly, whereas any key that needs a default, a transformation or a condition remains a function, as the following table summarizes.

Situation Recommended approach
Sort or group by one or several fields itemgetter or attrgetter
Nested attributes attrgetter with dotted names
Method without arguments as key The unbound method, such as str.lower
Method with fixed arguments methodcaller
Missing fields or computed keys A lambda or a named function
Mixed sort directions Successive stable sorts, secondary key first
Key function sent to another process A getter, which can be pickled
Sum of numbers The built-in sum, not reduce(operator.add, ...)

Key functions of this kind are interchangeable strategies, as examined in the article devoted to the Strategy pattern, and they serve as the key of groupby and the other tools described in the article devoted to itertools.

Conclusion

It is concluded that the module operator replaces the most common small lambdas with named, picklable callables: itemgetter and attrgetter read fields, methodcaller calls methods, and the arithmetic functions stand for the operators. This magic has a measured size: key extraction becomes about twice as fast, but a complete sort gains roughly 15 percent, and a getter cannot supply defaults or mixed directions. Mapping large files into memory with the module mmap, so that their contents can be read and searched without loading them whole, is the subject of a future article of this series.