-1

I tried the following command line in python

In[1]: ~(True ^ False)

and it returned :

Out[1]: -2

Could someone explain this to me please?

Thanks in advance

aka
  • 41
  • 4
  • 1
    Does this answer your question? [The tilde operator in Python](https://stackoverflow.com/questions/8305199/the-tilde-operator-in-python) – n8sty Jul 20 '20 at 16:02
  • (True ^ False) returned True (i.e. 1 in integer form). ~ operator is one's complement (for example : ~x => -(x+1)). So ~True or ~1 will be -(1+1) i.e. -2. – ClassHacker Jul 20 '20 at 16:05

1 Answers1

1

It's because of how python handles booleans:

True is represented as 1, (See True==1)

False is represented as 0. (See False==0)

Without syntactic sugar and abstractions:

x=~(1 ^ 0)
x=~1
x=-2
JCWasmx86
  • 3,473
  • 2
  • 11
  • 29
  • and why ~1 gives -2 – aka Jul 20 '20 at 16:06
  • It flips all bits. 1 is in binary `00000001`, if you apply bitwise not, it is changed to: `111111...(set bits)...111110`. Each set bit is unset and each unset bit is set now. – JCWasmx86 Jul 20 '20 at 16:12
  • One way to view tilde operator is as `~x = (-1) - x` – harold Jul 20 '20 at 16:12
  • But then if I replace with 2 numpy boolean arrays A and B of the same shape, ~(A ^ B) works well (i.e it returns an array of booleans). Why is it the case? – aka Jul 20 '20 at 16:26
  • 1
    @aka, the discrepancy you mention between pure Python and numpy is discussed here: https://joergdietrich.github.io/python-numpy-bool-types.html – dannyadam Jul 20 '20 at 19:35