Python Glossary Русский

all Python 3operatorfunction

operator.invert

bitwise

Bitwise inversion ~a (equal to -a-1 for int).

Syntax

operator.invert(a)

For ints the result is always -a - 1, because Python integers have no fixed width: ~5 gives -6, not 250 as an 8-bit type would. For a mask of a given width add & 0xFF. Do not use it on bools: ~True is -2, not False; since Python 3.12 this emits a DeprecationWarning, with removal planned for 3.16. Use not for logical negation.

Examples

import operator
print(operator.invert(0))   # → -1
print(operator.invert(5) == ~5)   # → True
print(operator.invert(5) == -5 - 1)   # → True
print(list(map(operator.invert, [1, 2, 3])))   # → [-2, -3, -4]
print(operator.invert(True))   # → -2 — с 3.12 DeprecationWarning: ~ над bool устарел

See also

Open in the full glossarydocs.python.orgReport an inaccuracy