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
?
Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument.
As an empty list is in fact just a empty collection, it will be converted to a boolean value of False .
Usually, an empty list has a different meaning than None ; None means no value while an empty list means zero values.
In Python, empty lists evaluate False , and non-empty lists evaluate True in boolean contexts. Therefore, you can simply treat the list as a predicate returning a Boolean value.
You are checking it against the literal value of the boolean False
. The same as 'A' == False
will not be true.
If you cast it, you'll see the difference:
>>> l = []
>>> l is True
False
>>> l is False
False
>>> l == True
False
>>> l == False
False
>>> bool(l) == False
True
The reason False == False
is true is because you are comparing the same objects. It is the same as 2 == 2
or '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 be False
:
None
False
(obviously)''
, []
, ()
0
, 0.0
, etc.{}
(an empty dict)len()
returns a 0
These are called "falsey" values. Everything else is "true". Which can lead to some strange things like:
>>> def foo():
... pass
...
>>> bool(foo)
True
It is also good to note here that methods that don't return an explicit value, always have None
as their return type, which leads to this:
>>> def bar():
... x = 1+1
...
>>> bool(bar)
True
>>> bool(bar())
False
An empty list is not the same as False
, but False
equals False
because it's the same object. bool(l)
returns False
because an empty list is "falsy".
In short, ==
is not bool() == bool()
.
For example, [1, 2] == [1, 2, 3]
is False
, even if the two are "truly".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With