Why does 1 == True but 2 != True in Python? [duplicate]
Possible Duplicate:
Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?
A brief transcript from my interactive console:
Python 2.7.2 (default, Jun 29 2011, 11:10:00)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> True
True
>>> 0 == True
False
>>> 1 == True
True
>>> 2 == True
False
Why on earth is this the case?
Edit: For the sake of contrast, consider the is
operator.
>>> 0 is False
False
>>> 1 is True
False
>>> 0 is 0
True
>>> True is True
True
That makes a lot of sense because though 1
and True
both mean the same thing as the condition of an if
statement, they really aren't the same thing.
Edit again: More fun consequences of 1 == True
:
>>> d = {}
>>> d[True] = "hello"
>>> d[1]
"hello"
Solution 1:
Because Boolean in Python is a subtype of integers. From the documentation:
Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to cast any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).
http://docs.python.org/library/stdtypes.html#boolean-values
Solution 2:
Because instances of bool
are also instances of int
in python. True
happens to be equals to integer 1
.
Take a look at this example:
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(True, int)
True
>>> int(True)
1
>>>
Solution 3:
It's standard binary conventions: 1 is true, 0 is false.
It's like 1 means "on" in machine language, and 0 means "off".
Because of this the bool
type is just a subtype of int
in Python, with 1 == True
and 0 == False
.
However any non-zero numeric value will be evaluated as True
in a conditional statement:
>>> if 2: print "ok"
ok
>>> 2 == True
False
Solution 4:
Once upon a time (in Python < 2.3), there was no boolean type, no False
or True
, only 0
and 1
. Then PEP 285 came along and thus they were added to the language. They were defined so that True == 1
and False == 0
, probably for reasons of backwards compatibility.