15.2. The operator Module
The operator module supplies functions that are equivalent to Python's operators. These functions are handy in cases where callables must be stored, passed as arguments, or returned as function results. The functions in operator have the same names as the corresponding special methods (covered in "Special Methods" on page 104). Each function is available with two names, with and without leading and trailing double underscores (e.g., both operator.add(a,b) and operator._ _add_ _(a,b) return a+b). Table 15-1 lists the functions supplied by the operator module.
Table 15-1. Functions supplied by the operator module
b in a
a is b
a is not b
a/b # "true" div -> no truncation
not not a, bool(a)
Module operator also supplies two higher-order functions whose results are functions suitable for passing as named argument key= to the sort method of lists, the sorted built-in function, and (in Python 2.5) other built-in functions such as min and max.
Returns a callable f such that f(o) is the same as getattr(o,attr).
Returns a callable f such that f(o) is the same as getitem(o,key).
For example, say that L is a list of lists, with each sublist at least three items long, and you want to sort L, in-place, based on the third item of each sublist. The simplest way is:
import operator L.sort(key=operator.itemgetter(2))