Why Does “~True” Result in -2 in Python?

Image credit: plotplot | Shutterstock.com

In this short article, I’ll try to explain why we get the following:

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 now it’s clear that bool is actually a subclass of int:

Having that said, ~True evaluates to:

The ~ operator is for bitwise inversion — it simply flips bits. So:

which is -2 in two’s complement. The ‘algorithm’ below describes how to get a number’s two’s complement:

  • Flip all the bits
  • add 1 to the resulting number
  • interpret the result as a binary representation of the magnitude
  • to determine the sign — if the original number begins with ‘1’, it’s negative, positive otherwise

“00000010” in binary is 2, but since the original number is “11111110”, which its MSB is “1”, the sign is determined as negative, and the final result would be “-2”.

I hope that was clear :)

Software engineer | Music geek | Beer lover

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store