What way is the best to check an empty list?

andrew cooke andrew at acooke.org
Wed Mar 25 16:19:56 EDT 2009


Andre Engels wrote:
> On Wed, Mar 25, 2009 at 4:21 PM, andrew cooke <andrew at acooke.org> wrote:
>> i will go against the grain slightly and say that "len" is probably the
>> best compromise in most situations (although i admit i don't know what
[...]
>> but i may be wrong - are there any containers (apart from pathological
>> hand-crafted examples) that would not define __len__()?
> When writing my answer, I thought of generators, but I now find that
> those will have boolean value 'true' whether or not they have
> something to generate, so they will go wrong under either method. The
> same holds for iterators. So for now I can't find any good example.


actually, the implication of what you said is probably worth emphasising
to the original poster: often you don't need to test whether a list is
empty or not, you simply iterate over its contents:

  for x in foo:
    # do something

this will then work with lists, tuples, sets, but also with iterators and
generators (which would give incorrect results in a test).  in all cases,
"do something" will not happen if there are no data to process.

andrew





More information about the Python-list mailing list