checking if a list is empty

Chris Torek nospam at torek.net
Wed May 11 15:05:03 EDT 2011


In article <4dcab8bf$0$29980$c3e8da3$5496439d at news.astraweb.com>
Steven D'Aprano  <steve+comp.lang.python at pearwood.info> wrote:
>When you call len(x) you don't care about the details of how to calculate 
>the length of x. The object itself knows so that you don't have to. The 
>same applies to truth testing.
>
>I have a data type that is an array of lists. When you call "if len(x) > 
>0" on it, it will blow up in your face, because len(x) returns a list of 
>lengths like [12, 0, 2, 5]. But if you say "if x", it will do the right 
>thing. You don't need to care how to truth-test my data type, because it 
>does it for you. By ignoring my type's interface, and insisting on doing 
>the truth-test by hand, you shoot yourself in the foot.

What this really points out is that "if x" and "if len(x) > 0" are
*different tests*.  Consider xml.etree.ElementTree "Element" objects.
The documentation says, in part:

    In ElementTree 1.2 and earlier, the sequence behavior means
    that an element without any subelements tests as false (since
    it's an empty sequence), even if it contains text and
    attributions. ...

    Note: This behavior is likely to change somewhat in ElementTree
    1.3.  To write code that is compatible in both directions, use
    ... "len(element)" to test for non-empty elements.

In this case, when x is an Element, the result of bool(x) *could*
mean just "x has sub-elements", but it could also/instead mean "x
has sub-elements, text, or attributions".

The issue raised at the beginning of this thread was: which test
is "better" when x is a list, the test that invokes bool(x), or
the test that invokes len(x)?  There is no answer to that, any more
than there is to which ice cream flavor is "best". [%]  A more
interesting question to ask, in any given bit of code, is whether
bool(x) or len(x) is more appropriate for *all* the types x might
take at that point, rather than whether one or the other is better
for lists, where the result is defined as equivalent.

(The biggest problem with answering that tends to be deciding
what types x might take.)

[% Chocolate with raspberry, or mint, or similar.]
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)      http://web.torek.net/torek/index.html



More information about the Python-list mailing list