What way is the best to check an empty list?

Andre Engels andreengels at gmail.com
Wed Mar 25 11:27:50 EDT 2009


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
> count is) because i think it will work when you expect it to and break
> when you have a bug in your program.
>
> using a simple boolean is more robust (and what i typically do in my own
> code because i am often too lazy to think carefully), but if it is given
> something that is not "list-like" you won't get an error until later in
> your code (and typically the sooner an error is found, the better).
>
> 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.


-- 
André Engels, andreengels at gmail.com



More information about the Python-list mailing list