How to know if a generator is empty from the start with Python?

Sometimes, we want to know if a generator is empty from the start with Python.

In this article, we’ll look at how to know if a generator is empty from the start with Python.

How to know if a generator is empty from the start with Python?

To know if a generator is empty from the start with Python, we can call next to see if the StopIteration exception is raised.

For instance, we write

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

res = peek(my_sequence)
if res is None:
    # ...
else:
    # ...

to define the peek function.

In it, we call next with iterable to see if the first item is returned or the StopIteration exception is raised.

If the error is raised, we return None.

Otherwise, we return first and the iterator that we get by calling chain with [first] and iterable which no longer has the first object.

Then we call peek to see is the returned result is None to see if the generator is empty.

Conclusion

To know if a generator is empty from the start with Python, we can call next to see if the StopIteration exception is raised.