I’m asking this because I know that the pythonic way to check whether a list is empty or not is the following:
my_list = []
if not my_list:
print "computer says no"
else:
# my_list isn't empty
print "computer says yes"
will print computer says no, etc. So this leads me to identify [] with False truth-values; however, if I try to compare [] and False “directly”, I obtain the following:
>>> my_list == False
False
>>> my_list is False
False
>>> [] == False
False
etc…
What’s going on here? I feel like I’m missing something really obvious.
The
ifstatement evaluates everything in a Boolean context, it is like there is an implicit call to thebool()built-in function.Here is how you would actually check how things will be evaluated by an
ifstatement:See the documentation on Truth Value Testing, empty lists are considered false, but this doesn’t mean they are equivalent to
False.PEP 285 also has some excellent information on why it was implemented this way, see the very last bullet in the Resolved Issues section for the part that deals with
x == Trueandx == Falsespecifically.The most convincing aspect to me is that
==is generally transitive, soa == bandb == cimpliesa == c. So if it were the way you expected and[] == Falsewere true and'' == Falsewere true, one might assume that[] == ''should be true (even though it obviously should not be in a language without implicit type conversion).