Python Glossary Русский

all Python 3operatorterm

operator

module

Python operators as functions: add, itemgetter, attrgetter and methodcaller instead of short lambdas.

Syntax

import operator

operator is used where a function wants a key or an action: sorted(rows, key=itemgetter(1)) reads shorter than a lambda and runs faster. itemgetter with several arguments returns a tuple, but with one it returns the bare value, which trips people up. For folding with functools.reduce there are operator.add and operator.mul.

Examples

from operator import itemgetter, add
rows = [('bob', 25), ('amy', 31), ('cat', 19)]
print(sorted(rows, key=itemgetter(1))[0])  # → ('cat', 19)
print(itemgetter(0)(rows[0]), itemgetter(0, 1)(rows[0]))  # → bob ('bob', 25)
print(add(2, 3))  # → 5

See also

Open in the full glossarydocs.python.orgReport an inaccuracy