[Tutor] What is the difference between checking false?
Steven D'Aprano
steve at pearwood.info
Sun Jun 16 07:32:38 CEST 2013
On 16/06/13 11:30, Jim Mooney wrote:
> ##This is puzzling me. If I check the equality of 0, None, empty
> string, and empty list with False,
> ##only zero satisfies the equality. But if I use them in a not
> statement, they all turn out False.
> ##What gives?
That's because the tests do different things. Equals tests whether two values have equal value; testing things with `if` tests whether they are true-ish or false-ish. Some languages require that the conditions in an `if` test be actual boolean values True or False, but Python does not. Partly for backwards compatibility, partly by design (but mostly by design), Python tests conditions according to the principle of "duck-typing":
"if it quacks like a duck and swims like a duck, it might as well be a duck".
Consequently, the Python philosophy is that, as a general rule, if you want to know whether an object is true-ish or false-ish, you should just see if it quacks like True or quacks like False.
This question came up a day or so ago, on another list. Here is one of my answers:
http://mail.python.org/pipermail/python-list/2013-June/649710.html
One advantage of this is that you can do things like:
if mylist and mylist[0] == item:
...
instead of:
if mylist != []:
if mylist[0] == item:
...
which is how things work in languages with strict true/false flags and no short-circuit testing, like Pascal.
--
Steven
More information about the Tutor
mailing list