Fix Python – Why does ~True result in -2?


Asked By – lukaszkups

In Python console:


Gives me:


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

Now we will see solution for issue: Why does ~True result in -2?


int(True) is 1.

1 is:


and ~1 is:


Which is -2 in Two’s complement1

1 Flip all the bits, add 1 to the resulting number and interpret the result as a binary representation of the magnitude and add a negative sign (since the number begins with 1):

11111110 → 00000001 → 00000010 
         ↑          ↑ 
       Flip       Add 1

Which is 2, but the sign is negative since the MSB is 1.

Worth mentioning:

Think about bool, you’ll find that it’s numeric in nature – It has two values, True and False, and they are just “customized” versions of the integers 1 and 0 that only print themselves differently. They are subclasses of the integer type int.

So they behave exactly as 1 and 0, except that bool redefines str and repr to display them differently.

>>> type(True)
<class 'bool'>
>>> isinstance(True, int)

>>> True == 1
>>> True is 1  # they're still different objects

This question is answered By – Maroun

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0