What way is the best to check an empty list?

John Machin sjmachin at lexicon.net
Wed Mar 25 16:29:58 CET 2009

On Mar 26, 2:21 am, "andrew cooke" <and... 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).

When you are doing something like
   if A and A[-1] == 'yadda':
you won't have to wait long for the exception if A is not
subscriptable :-)

> but i may be wrong - are there any containers (apart from pathological
> hand-crafted examples) that would not define __len__()?

Very unlikely.

More information about the Python-list mailing list