0 == False but [] != False?
Rex Turnbull
rex at no_spam.dicad.de
Thu May 24 07:21:50 EDT 2007
Steven D'Aprano :
> On Thu, 24 May 2007 06:59:32 +0000, Tim Roberts wrote:
>
>> As a general rule, I've found code like "if x == False" to be a bad idea in
>> ANY language.
>
>
> Surely that should be written as "if (x == False) == True"?
>
>
Why compare to False?
" if not x : ... "
It really doesn't matter if x is False or if it evaluates to False. Many
things evaluate to False like [], (), 0, "", None and a few other things.
>>> def tf(thing):
... if thing : print "True thing", thing
... elif not thing : print "False thing",thing
... else : print "No thing"
...
>>> tf([])
False thing []
>>> tf([1])
True thing [1]
>>> a = ()
>>> tf(a)
False thing ()
>>> a=(0)
>>> tf(a)
False thing 0
>>> a= (1,2,3)
>>> tf(a)
True thing (1, 2, 3)
>>> tf("abc")
True thing abc
>>> tf("")
False thing
>>>
More information about the Python-list
mailing list