How do I know if a generator is empty from the start?

Dan picture Dan · Mar 19, 2009 · Viewed 76.6k times · Source

Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?

Answer

John Fouhy picture John Fouhy · Mar 19, 2009

Suggestion:

def peek(iterable):
    try:
        first = next(iterable)
    except StopIteration:
        return None
    return first, itertools.chain([first], iterable)

Usage:

res = peek(mysequence)
if res is None:
    # sequence is empty.  Do stuff.
else:
    first, mysequence = res
    # Do something with first, maybe?
    # Then iterate over the sequence:
    for element in mysequence:
        # etc.