checking if a list is empty

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat May 21 21:02:25 EDT 2011


On Sat, 21 May 2011 15:46:01 +0100, John J Lee wrote:

> In the absence of an explicit interface declaration (have any standards
> emerged for that in Python 3, BTW?), the use of len() does give you some
> information about the interface, which sometimes makes it easier to
> change the function.

Er, yes? But in any realistic example (your trivial function xyzzyx below 
is not very realistic) you'll almost certainly get additional hints in 
the function body. If you have your stereotypical badly-documented 
function that does this:

def spam(x):
    if x:
        print("no")
    # ...
    x.append(42)
    # ...

that's a hint that x is actually meant to be a list. If instead it says

    x += 42

that's a good hint that x should not be a list. In either case, changing 
the test from "if x" to "if x == []" or "if len(x) == 0" or "if x == 0" 
doesn't gain you anything except a slightly longer average line length. 
If you're being paid by the character, that's an advantage, but 
otherwise, why bother?

True, if the function is sufficiently trivial, as in your xyzzyx example, 
then there won't be any such hints as to what sort of input the function 
expects. If that's the case, then chances are that the function accepts 
*any* object:

> def xyzzy(x):
>     if x:
>         print "yes"

and changing its semantics to only accept (say) lists, as in your 
example, is a risky thing to do.

It is *much* safer to leave that function untouched, create a new one:

def my_xyzzy(alist):
    if alist:
        print "probably"
    if len(alist) == 1:
        print "definitely"         

and then change the calls to xyzzyx into my_xyzzyx when and as you 
determine that it is safe to do so. That will ensure that if you miss a 
call of xyzzyx(42) somewhere deep in the library, the code will continue 
to run. If not, you'll have a dead function. You can always take it out 
later, once you are confident that it is indeed dead code.


[...]
> If it's written this way, it's clear that it can't be None:
> 
> def xyzzy(x):
>     if len(x) != 0:
>         print "yes"


But you're assuming that the function actually is intended to accept only 
objects with a __len__ method. If that is the author's intention, there 
are better ways of signaling that fact.

I'm not entirely sure what your point is... is it to encourage lazy 
programmers to write "len(x)==0" instead of documentation and meaningful 
names, or are you just pointing out the occasional silver-lining to a 
practice which is generally and usually unnecessary?



-- 
Steven



More information about the Python-list mailing list