empty lists vs empty generators

Brian Roberts brian at mirror.org
Mon May 2 19:14:57 EDT 2005


I'm using using generators and iterators more and more intead of
passing lists around, and prefer them.  However, I'm not clear on the
best way to detect an empty generator (one that will return no items)
when some sort of special case handling is required.

Typical code for handling an empty list:
    if somelist:
        for x in somelist: 
            something(x)
    else:
        empty_list_special_case

But this doesn't work with iterators -- a generator is "true"
regardless of whether its going to return any items.  (I understand
why).

The closest equivalent I know of is:
    n = 0
    for n, x in enumerate(somegenerator()):
       something(x)
    if n == 0:
       empty_list_special_case

Which seems rather awkward -- doesn't read as easily for me, and
introduces another variable.

Q1: Is there a better or alternate way to handle this?
Q2: Is there a way that handles both lists and generators, so I don't
have to worry about which one I've got?

Thanks,
Brian.



More information about the Python-list mailing list