The Python Oracle

Why does 1 == True but 2 != True in Python?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Light Drops

--

Chapters
00:00 Why Does 1 == True But 2 != True In Python?
00:51 Answer 1 Score 13
01:21 Answer 2 Score 28
01:40 Accepted Answer Score 37
02:20 Answer 4 Score 5
02:29 Thank you

--

Full question
https://stackoverflow.com/questions/7134...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 37


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




ANSWER 2

Score 28


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
>>> 



ANSWER 3

Score 13


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



ANSWER 4

Score 5


Equality testing is different than boolean testing:

>>> bool(1)
True
>>> bool(2)
True
>>> bool(-1)
True
>>> bool(0)
False