What way is the best to check an empty list?

Carl Banks pavlovevidence at gmail.com
Thu Mar 26 00:24:47 CET 2009

On Mar 25, 1:19 pm, "andrew cooke" <and... at acooke.org> wrote:
> 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.

Which is fine as long as you don't need to do something else in the
case of no items.  But in that case you have no choice but to iterate
and see if any items are produced.  There are some iterables for which
no if-test at all works.

Carl Banks

More information about the Python-list mailing list