pythoniterator

One-liner to check whether an iterator yields at least one element?


Currently I'm doing this:

try:
    something = next(iterator)
    # ...
except StopIteration:
    # ...

But I would like an expression that I can place inside a simple if statement. Is there anything built-in which would make this code look less clumsy? I only need to check for the first item.


Solution

  • if any(True for _ in iterator):
        print('iterator had at least one element')
    
    if all(False for _ in iterator):
        print('iterator was empty')
    

    Note that this will consume the first element of the iterable if it has at least one element.