Why do integers compare equal to booleans?

duncan smith duncan at invalid.invalid
Fri Nov 16 10:17:28 EST 2018


On 16/11/18 14:51, Steve Keller wrote:
> Why do the integers 0 and 1 compare equal to the boolean values False
> and True and all other integers to neither of them?
> 
>     $ python3
>     Python 3.5.2 (default, Nov 12 2018, 13:43:14)
>     [GCC 5.4.0 20160609] on linux
>     Type "help", "copyright", "credits" or "license" for more information.
>     >>> 0 == False
>     True
>     >>> 1 == True
>     True
>     >>> 2 == False
>     False
>     >>> 2 == True
>     False
>     >>> -1 == False
>     False
>     >>> -1 == True
>     False
>     >>>
> 
> Since these are objects of different types I would expect they cannot
> be equal.  I know that 0 means false and != 0 means true in C, C++,
> etc. but in Python that surprises me.
> 
> Steve
> 

>>> isinstance(False, int)
True
>>> isinstance(True, int)
True
>>> False.real
0
>>> True.real
1
>>>

At least in recent Pythons.

Duncan



More information about the Python-list mailing list