Sub topic 12
itemgetter, attrgetter and operator functions
This chapter assumes you can write a lambda, pass a key function to sorted, and index into tuples, lists and dictionaries. It covers the operator module, which provides ready-made function versions of Python's operators. These often replace small lambdas.
Why the operator module exists
A lambda such as lambda p: p[1] only indexes its argument. Python's operator module offers this and many other operations as named, reusable callables. They have two advantages over a lambda. They state the intent directly, and they are implemented in C, so they usually run faster.
itemgetter: indexing as a function
operator.itemgetter(n) returns a function that fetches item n from whatever you give it. It works with tuples, lists and dictionaries, because it uses the same [] lookup.
from operator import itemgetter
pairs = [("apple", 3), ("pear", 1), ("fig", 2)]
print(sorted(pairs, key=itemgetter(1)))
# [('pear', 1), ('fig', 2), ('apple', 3)]
prices = {"apple": 3, "pear": 1, "fig": 2}
print(max(prices.items(), key=itemgetter(1)))
# ('apple', 3)Given several indexes, itemgetter returns a tuple of the values. This is a compact way to sort by more than one field.
from operator import itemgetter
rows = [
{"name": "Ada", "team": "b", "age": 36},
{"name": "Bo", "team": "a", "age": 29},
{"name": "Cy", "team": "a", "age": 41},
]
by_team_then_age = sorted(rows, key=itemgetter("team", "age"))
print([r["name"] for r in by_team_then_age])
# ['Bo', 'Cy', 'Ada']attrgetter: attribute access as a function
operator.attrgetter("name") does for attributes what itemgetter does for indexes. It also accepts dotted names such as "address.city", and several names at once.
from dataclasses import dataclass
from operator import attrgetter
@dataclass
class Player:
name: str
score: int
players = [Player("Ada", 70), Player("Bo", 95), Player("Cy", 82)]
best = sorted(players, key=attrgetter("score"), reverse=True)
print([p.name for p in best])
# ['Bo', 'Cy', 'Ada']Operator functions
The module also exposes the operators themselves as functions: add, mul, sub, truediv, eq, lt, contains and others. They are most useful as arguments to higher-order functions, in place of lambda a, b: a + b.
from functools import reduce
from operator import mul
print(reduce(mul, [1, 2, 3, 4], 1)) # 24Combined with partial, they build small one-argument functions:
from functools import partial
from operator import mul
triple = partial(mul, 3)
print(list(map(triple, [1, 2, 3]))) # [3, 6, 9]The table shows common lambdas and their operator equivalents.
| Lambda | Operator version |
|---|---|
| `lambda x: x[1]` | `itemgetter(1)` |
| `lambda x: (x[0], x[2])` | `itemgetter(0, 2)` |
| `lambda x: x.score` | `attrgetter("score")` |
| `lambda a, b: a * b` | `mul` |
Common errors
- Calling instead of passing. Write
key=itemgetter(1), notkey=itemgetter(1)(row).itemgetter(1)is the function you pass. - Wrong tool for the data. Use
itemgetterfor items reached with[]andattrgetterfor attributes.itemgetter("score")on an object fails with aTypeError, because the object is not subscriptable. - Expecting a single value. With more than one index or name, the result is a tuple.
- Forcing it. If the lambda computes something, such as
lambda p: p[1] * 2, no operator function replaces it. Keep the lambda.
Exercise
You have people, a list of objects with .last and .first string attributes. Write one expression that sorts them by last name, then by first name, without using a lambda.
Show answer
sorted(people, key=attrgetter("last", "first")), after from operator import attrgetter. With two names, attrgetter returns a tuple (last, first) for each object, and tuples compare element by element.
Exercise
Why can itemgetter(1) not replace lambda p: p[1] + 1?
Show answer
itemgetter(1) only fetches the item. It cannot add anything to it, so the computation still needs a lambda or a def.