Python Glossary Русский

all Python 3operatorfunction

operator.getitem

sequences

Item access: a[b].

Syntax

operator.getitem(a, b)

The second argument may be a slice: getitem(s, slice(1, 3)) is the same as s[1:3]. A missing key raises KeyError and an out-of-range index raises IndexError; there is no safe default variant — dicts have dict.get. When the key is fixed and the function is reused, prefer operator.itemgetter: the function is built once and reads more clearly than partial(getitem, …).

Examples

import operator
print(operator.getitem([10, 20, 30], 1))   # → 20
print(operator.getitem({'a': 1, 'b': 2}, 'b'))  # → 2
print(operator.getitem([10, 20, 30], slice(0, 2)))  # → [10, 20]
rows = [(1, 'anna'), (2, 'boris')]
print([operator.getitem(r, 1) for r in rows])  # → ['anna', 'boris']
print(operator.getitem([10, 20, 30], 5))  # → IndexError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy