This may be simply idiotic, but for me it’s a bit confusing:
In [697]: l=[]
In [698]: bool(l)
Out[698]: False
In [699]: l == True
Out[699]: False
In [700]: l == False
Out[700]: False
In [701]: False == False
Out[701]: True
Why does l==False return False while False == False returns True?
You are checking it against the literal value of the boolean
False. The same as'A' == Falsewill not be true.If you cast it, you’ll see the difference:
The reason
False == Falseis true is because you are comparing the same objects. It is the same as2 == 2or'A' == 'A'.The difficulty comes when you see things like
if l:and this check never passes. That is because you are checking against the truth value of the item. By convention, all these items will fail a boolean check – that is, their boolean value will beFalse:NoneFalse(obviously)'',[],()0,0.0, etc.{}(an empty dict)len()returns a0These are called “falsey” values. Everything else is “true”. Which can lead to some strange things like:
It is also good to note here that methods that don’t return an explicit value, always have
Noneas their return type, which leads to this: