variable - what does it mean to return true in python

Why does ~True result in-2? (2)

~True == -2 is not surprising if True means 1 and ~ means bitwise inversion...

...provided that

  • True can be treated as an integer and
  • integers are represented in Two's complement


  • fixed the mixing between integer representation and bitwise inversion operator
  • applied another polishing (the shorter the message, the more work needed)

In Python console:


Gives me:


Why? Can someone explain this particular case to me in binary?

The Python bool type is a subclass of int (for historical reasons; booleans were only added in Python 2.3).

Since int(True) is 1, ~True is ~1 is -2.

See PEP 285 for why bool is a subclass of int.

If you wanted the boolean inverse, use not:

>>> not True
>>> not False

If you wanted to know why ~1 is -2, it's because you are inverting all bits in a signed integer; 00000001 becomes 1111110 which in a signed integer is a negative number, see Two's complement:

>>> # Python 3
>>> import struct
>>> format(struct.pack('b', 1)[0], '08b')
>>> format(struct.pack('b', ~1)[0], '08b')

where the initial 1 bit means the value is negative, and the rest of the bits encode the inverse of the positive number minus one.