all Python 3operatorfunction
operator.neg
arithmetic
Return −a (unary negation).
Syntax
operator.neg(a)
It works as a descending sort key for numbers: sorted(xs, key=operator.neg). That does not work for strings — use reverse=True there. Floats keep the sign even for zero: neg(0.0) gives -0.0, visible when printed and through math.copysign. A user class supports neg by defining __neg__.
Examples
import operator
print(operator.neg(3)) # → -3
print(operator.neg(3) == -3) # → True
print(list(map(operator.neg, [1, -2, 3]))) # → [-1, 2, -3]
print(sorted([3, 1, 2], key=operator.neg)) # → [3, 2, 1]
print(operator.neg(True)) # → -1
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy