checking if a list is empty
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed May 11 09:36:02 EDT 2011
On Wed, 11 May 2011 10:14:38 +0100, Hans Georg Schaathun wrote:
> In this case, the interpretation of an arbitrary object as a boolean is
> peculiar for python.
Incorrect. It is widespread among many languages. Programmers have been
writing conditional tests using arbitrary values since 1958 when Lisp
introduced the concept.
C, Forth and Visual Basic treat any non-zero number as true, and zero as
false; that's not quite arbitrary objects, but it's arbitrary integer
values. Similarly, Objective C has two different boolean types, "BOOL"
which is a C char where 0 is false and everything else is true, and
"bool" which is more like the Java boolean type.
Perl treats the empty string, "0", 0 and undefined variables as false,
and everything else as true.
Ruby treats null and false as false, and everything else as true.
JavaScript treats "", null, undefined, NaN, 0 and false as false values,
and everything else as true.
PHP treats FALSE, 0, "", "0", empty arrays, objects with no member
variables, NULL, unset variables, and SimpleXML objects created from
empty tags as false, everything else as true.
Clojure treats nil and false as false, everything else as true.
SQL's boolean type has three or four values: true, false, null and
unknown, where implementations are free to treat null and unknown as
either the same or different values. (So a 3 or 4 value logic, not
actually Boolean at all.)
So Python is hardly unique, nor is this some new-fangled innovation.
> An empty list is a real, existing object, and the
> supposition that [] be false is counter-intuitive.
Not to me, nor to anyone who has an intuition about "something" versus
"nothing". I believe this distinction is fundamental to the universe, and
that nearly every person understands this intuitively. The distinction
between something and nothing is so strong that it took centuries of
argument for the finest minds in Europe[1] to finally decide that, yes,
zero is a number -- and they only did it because the Arabs and Indians
had proven how useful it was, and Roman numerals really do suck for doing
calculations.
> It can be learnt,
> and the shorthand may be powerful when it is, but it will confuse many
> readers.
In my experience, it does not confuse newbies or beginners. The only
people it confuses are those who are over-educated into thinking that the
One Correct Way of doing truth testing is with a dedicated boolean type,
and anything else is heresy.
[1] At least is you asked them.
--
Steven
More information about the Python-list
mailing list