checking if a list is empty

harrismh777 harrismh777 at charter.net
Mon May 9 20:10:18 EDT 2011


Steven D'Aprano wrote:
>      Python uses a boolean algebra where there are many ways of
>      spelling the true and false values. The "not" operator returns
>      the canonical bool values:

>      Take note of the distinction between lower-case true/false,
>      which are adjectives, and True/False, which are objects of
>      class bool.

    Yes, yes... to your previous comments, and to move the discussion 
forward a bit...

...  the interesting thing about this part of the discussion is the 
class bool... because it looks like 'list' is being 'promoted' to type 
class bool in the following:

     if not list:   <=== this is not logical on the surface...

... if the equivalent is:

     if not bool(list):   <=== this is more explicit, and more readable 
although it still doesn't tell a casual reader how the bool(list) 
evaluates... is it empty? is it name exception? other?   I'm just 
saying; no need to respond...  just that its easier to understand the 
syntax of 'not list' in the knowledge that what is happening under the 
hood is that the 'not' operator does require a bool() and that list is 
being evaluated bool(list) as one of two logical states.


     Having played around a little bit with this today I am again 
impressed that bool() can take *any* object as a parm and derive the 
correct binary state, whatever that happens to be:

bool({})     False
bool([])     False
bool(0)      False
bool('')     False
bool(())     False


    Therefore,

    if not str      tests for the empty string...

    if not dict     tests for the empty dictionary...

    &etc.


     ... is at least consistent ...


kind regards,
m harris






More information about the Python-list mailing list