Python Reference ยท Standard Library: Data Structures and Functional Tools
The operator module
Reference for Python's operator module: operators as functions, itemgetter, attrgetter, methodcaller, in-place variants and using them with sorted, map and reduce.
The operator module exposes Python's operators as ordinary functions: operator.add(a, b) does what a + b does. That is useful whenever an API wants a function, such as reduce, map or a sort key.
Three factories, itemgetter, attrgetter and methodcaller, build small fast callables that fetch items, attributes or call methods. They replace many short lambdas.
from operator import itemgetter rows = [("b", 2), ("a", 1)] print(sorted(rows, key=itemgetter(1)))
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
operator.add(a, b) operator.itemgetter(*items) operator.attrgetter(*attrs) operator.methodcaller(name, /, *args, **kwargs)
| Group | Functions |
|---|---|
| Arithmetic | add, sub, mul, truediv, floordiv, mod, pow, neg, pos, abs, matmul |
| Comparison | lt, le, eq, ne, ge, gt |
| Logical and identity | not_, truth, is_, is_not |
| Bitwise | and_, or_, xor, invert, lshift, rshift |
| Sequences | concat, contains, countOf, indexOf, getitem, setitem, delitem |
| In-place | iadd, isub, imul, iconcat, ... |
Return value: the result of the corresponding operator. itemgetter and attrgetter return a single value for one key and a tuple for several; methodcaller returns a callable that, applied to an object, returns the method's result.
Raises: whatever the underlying operation raises (TypeError, KeyError, AttributeError, ...).
Usage notes
- Names ending in
_(and_,or_,not_,is_) avoid clashes with keywords. Dunder aliases such asoperator.__add__also exist. - Short-circuit operators are not available.
andandorcannot be functions because they must not evaluate the right side early;operator.and_is the bitwise&. attrgettersupports dotted paths:attrgetter("address.city")follows nested attributes.itemgetterworks with any__getitem__: dicts, lists, tuples, and strings. With several items it returns a tuple, which gives you multi-key sorts for free.- In-place functions return the result, and for immutable types (numbers, strings, tuples) that is a new object; only for mutable types such as lists is the original changed. Always use the return value.
- Speed: these callables are implemented in C and usually beat an equivalent lambda in a sort key.
- Readability beats cleverness.
lambda a, b: a + bis fine in a one-off; reach foroperatorfor the common cases above.