~

Flip every bit — with unbounded ints that means ~a == -a - 1, always.

Bitwise operatorPython 1.0+Live demo
Common call
~n
Returns
int: -a - 1
Replaces
~0 is -1, ~5 is -6, ~-1 is 0
Watch out
~ is not logical negation — that is `not`
~aaThe int to invert. Floats raise TypeError.type: int · required
int

Demo

Live evaluation
Try:
Inputs
aintthe int
Output
~5
-6

Python ints have no fixed width, so "flip all bits" is defined arithmetically: ~a is exactly -a - 1. Hence ~0 → -1 and ~-1 → 0.

Operands

NameTypeRequiredDescription
aintyesThe int to invert. Floats raise TypeError.

Return value

intThe two’s-complement inversion: every bit flipped, which for Python’s unbounded ints is exactly -a - 1.

Common patterns

Building masks
Clear specific bits by AND-ing with an inverted mask.
flags &= ~DIRTY_BIT   # clear one flag
Index-from-end trick
~i equals -(i+1), pairing first↔last in one expression.
for i in range(len(s) // 2):
    if s[i] != s[~i]:   # palindrome check
        return False

Examples

1. Positive int
~5
Returns
-6
2. Zero
~0
Returns
-1
3. Negative int
~-1
Returns
0

Pitfalls

1. ~ on a bool is an int trap
~True is -2 — historically legal, deprecated in 3.12+ precisely because it confuses.
Surprising
~True
-2 (DeprecationWarning in 3.12+)
Fix
not flag
logical negation
2. Expecting an unsigned flip
There is no fixed width — mask explicitly for N-bit behavior.
Negative result
~0b1010
-11, not 0b0101
4-bit flip
~0b1010 & 0b1111
5 (0b0101)

When to use

Use it
  • Clearing flag bits with & ~mask
  • The ~i index-from-end idiom
Reach for something else
  • Logical negation → not
  • Fixed-width complement → mask with & ((1 << n) - 1)

Notes

Complexity
O(bits)
Return
int
CPython impl
Objects/longobject.c :: long_invert → __invert__
Memory
No allocation for small ints
Thread-safe
Yes — pure computation

FAQ

Two’s complement with unlimited bits: flipping every bit of a is arithmetically -a - 1. A fixed-width language shows you the masked version of the same number.

History

3.12
~ on bool deprecated.
1.0
Core operator from the beginning.