checking if a list is empty

Eric Snow ericsnowcurrently at gmail.com
Fri May 6 16:00:02 EDT 2011


On Fri, May 6, 2011 at 1:31 PM, Terry Reedy <tjreedy at udel.edu> wrote:

> On 5/6/2011 7:34 AM, James Mills wrote:
>
>> On Fri, May 6, 2011 at 4:36 PM, Jabba Laci<jabba.laci at gmail.com>  wrote:
>>
>>> If I want to check if a list is empty, which is the more pythonic way?
>>>
>>
>> [...]
>>
>>  (2) if not li:
>>>
>>
>> This is fine.
>>
>
> This is the intended way. Anything in addition is extra noise and wasted
> calculation. In other words, let Python do the boilerplate work for you.
>
>
That works for lists, but for a class that implements a list-like interface,
subclassing list or not, it will not always work the way you want.  The
language reference indicates that, for the implicit cast to a bool, __bool__
is checked on the object, then __len__, and then it defaults to True [1].
 So the above only works the way you expect if __len__ is the normal length
for a list and __bool__ is not defined.

I ran into this once when I had a class that defined __len__ but wanted the
object to cast to True no matter what.  For my case I chose to redefine
__bool__.

So it seems like this boils down to what you want to know.  Is the list
empty (length 0) or is the boolean version false?  Again, for lists these
are the same.  For list-like classes they are not necessarily the same.

Incidently, you can also check "if li == []:".  This will let the __eq__
operator jump in.

-eric

[1] http://docs.python.org/dev/py3k/reference/datamodel.html#object.__bool__

-- 
> Terry Jan Reedy
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110506/11ba58ed/attachment.html>


More information about the Python-list mailing list