loading...

Why Does "~True" Result in -2 in Python?

marounmaroun profile image Maroun Maroun ・1 min read

If you try the following in your console:

~True

you'll get "-2" 😳. Why?

Think about bool, you'll find that it is numeric in nature - It can hold two values, "True" and "False", and they are just "customized" versions of the integers 1 and 0 that only print themselves differently.

So bool is a subclass of int:

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

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

Having that said, ~True evaluaes to:

~True == ~int(True) == ~1 == -2

~ simply flips the bits. So:

1  = 00000001
~1 = 11111110

which is -2 in two's complement. Verifying that:

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.

I hope that was clear :)

Posted on by:

marounmaroun profile

Maroun Maroun

@marounmaroun

Nice to meet you 🍻 My name is Maroun. I'm a dad, musician, programmer, Stackoverflower and astronaut wannabe.

Discussion

pic
Editor guide