checking if a list is empty

Hans Georg Schaathun hg at schaathun.net
Wed May 11 05:02:42 EDT 2011


On 07 May 2011 02:51:50 GMT, Steven D'Aprano
  <steve+comp.lang.python at pearwood.info> wrote:
:  On Fri, 06 May 2011 14:57:21 -0700, scattered wrote:
: 
: > is there any problem with
: > 
: > (3) if li == []:
: > 
: > ?
: > 
: > Seems to work when I test it and seems to clearly test what you are
: > trying to test. The only problem might be if in some contexts == has the
: > semantics of checking for object identity.
: 
:  Yes, if li == [] works too. But how do you know li is a list and not some 
:  other sequence type?

It says so in the Subject header :-)

:  The advantage of the "if x" test is that it is independent of the type of 
:  x.

Sure, but the question wasn't ...

The problem with 'if x' is that it requires a much more detailed 
understanding of python.  li == [] is as explicit as it gets, and
leaves no room for doubt.  len(li) == 0 is almost as explicit and
much more flexible.  Just x is as generic as it gets, but depends
on python's convolved rules for duck processing and if you aim at
legibility it is better avoided.


-- 
:-- Hans Georg



More information about the Python-list mailing list