Python Glossary Русский

all Python 3operatorfunction

operator.itemgetter

calls and access

A factory returning a callable that fetches items by fixed index/key.

Syntax

f = operator.itemgetter(index)

The number of keys changes the result's shape: itemgetter(1) returns the item itself, while itemgetter(1, 2) returns a tuple. That is a trap in generated code where there might be a single key. It works with dicts and with slices: itemgetter(slice(0, 2)). It is faster than a lambda and, unlike one, can be pickled; hence its popularity in key= for sorted, min and max.

Examples

import operator
g = operator.itemgetter(1)
print(g([10, 20, 30]))   # → 20
print(operator.itemgetter(1)([10, 20, 30]) == [10, 20, 30][1])   # → True
print(operator.itemgetter(0, 2)('abcd'))   # → ('a', 'c')
print(operator.itemgetter('b')({'a': 1, 'b': 2}))   # → 2
pairs = [('a', 3), ('b', 1)]
print(sorted(pairs, key=operator.itemgetter(1)))   # → [('b', 1), ('a', 3)]

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy