all Python 3operatorfunction
operator.sub
arithmetic
Return a − b (the functional form of `-`).
Syntax
operator.sub(a, b)
Argument order matters: sub(a, b) is a − b, not b − a. It is easy to get wrong with functools.partial: partial(operator.sub, 10) gives x → 10 − x, not x − 10. For "subtract a constant" a lambda reads better. For sets sub is the difference: sub({1, 2, 3}, {2}) returns {1, 3}.
Examples
import operator
import functools
print(operator.sub(5, 2)) # → 3
print(operator.sub(5, 2) == 5 - 2) # → True
print(list(map(operator.sub, [10, 20, 30], [1, 2, 3]))) # → [9, 18, 27]
print(functools.reduce(operator.sub, [100, 20, 3])) # → 77
print(operator.sub("ab", "a")) # → TypeError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy