The operator module exposes common operations as functions. itemgetter reads indexes or mapping keys, while attrgetter follows attributes, including paths such as customer.name. They fit sorted, min, max, map, and grouping workflows.

from operator import attrgetter, itemgetter

rows = [("Ana", 91), ("Beto", 84), ("Caio", 96)]
ranking = sorted(rows, key=itemgetter(1), reverse=True)

class User:
    def __init__(self, name: str) -> None:
        self.name = name

names = list(map(attrgetter("name"), [User("Ana"), User("Beto")]))

How to use it safely

Choose itemgetter for sequences and mappings, and attrgetter for objects. A lambda is clearer when the rule performs a transformation, supplies a default, or validates input. Do not hide accesses that may fail: document required keys and attributes.

To strengthen the foundation, read Python collections guide and type hints guide.

The official Python documentation, accessed July 22, 2026, describes the API, edge cases, and version compatibility.