-1

I always thought that ~ was equivalent to not in Python, but I had a bug that made me find out this. Could someone explain to me what that is?

Thanks

Chiekh
  • 19
  • 4

1 Answers1

2

From the official documentation:

The unary ~ (invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion of x is defined as -(x+1). It only applies to integral numbers.

As to why ~False would be -1, it's because for historical reasons False == 0 and True == 1 (they're not identical but they are equal, and bool is a subclass of int). If you apply the formula above, you get ~False => -(False + 1) => -(0+1) => -1, QED.

Masklinn
  • 34,759
  • 3
  • 38
  • 57