'Effect of tilde on booleans — why ~True is -2 & ~False is -1 in Python? [duplicate]

I found that ~True is -2 and ~False is -1. Why is this?

W3Schools says that ~ inverts all the bits. Why isn't ~True is False and ~False is True?

Reasoning attempts

My attempt to explain these:

True is +1, and the bits of +1 are inverted. + is inverted to -. 1 in two-digit binary is 01, so inverted bits: 10, ie 2. So result is -2.

False is +0, + is inverted to -, 0 in two-digit binary is 00, all the bits inverted, 11, which is 3 - it should be 1.

Sources

This answer paints a more complicated picture:

A list full of Trues only contains 4- or 8-byte references to the one canonical True object.

The PyTables User’s Guide says:

bool: Boolean (true/false) types. Supported precisions: 8 (default) bits.

These don't support the simplistic (and apparently wrong) reasoning above.



Solution 1:[1]

First of all, I'd use the not operator to invert Boolean values (not True == False, and vice versa). Now if Booleans are stored as 8-bit integers, the following happens:

True is 0000 0001. Hence ~True yields 1111 1110, which is -2 in two's-complement representation.

False is 0000 0000. Hence ~False yields 1111 1111, which is -1.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wjandrea