What way is the best to check an empty list?

andrew cooke andrew at acooke.org
Wed Mar 25 16:21:34 CET 2009


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__()?

andrew


srinivasan srinivas wrote:
>
> For ex: to check list 'A' is empty or not..
> if A == []:
> if A.count == 0:
> if len(A) == 0:
> if not A:
>
> Thanks,
> Srini
>
>
>       Add more friends to your messenger and enjoy! Go to
> http://messenger.yahoo.com/invite/
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>





More information about the Python-list mailing list