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

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.

Leave a Comment