"0 in [True,False]" returns True

David Wahler dwahler at gmail.com
Mon Dec 12 21:46:23 EST 2005

Pierre Quentel wrote:
> Hi all,
> In some program I was testing if a variable was a boolean, with this
> test : if v in [True,False]
> My script didn't work in some cases and I eventually found that for v =
> 0 the test returned True
> So I changed my test for the obvious "if type(v) is bool", but I still
> find it confusing that "0 in [True,False]" returns True

>From the docs: Python Library Reference, section
"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."

I don't blame you for not knowing about this; it is rather unintuitive.

-- David

More information about the Python-list mailing list