Currently I\'m doing this:
try:
something = iterator.next()
# ...
except StopIteration:
# ...
But I would like an expression th
The best way to do that is with a peekable from more_itertools.
from more_itertools import peekable
iterator = peekable(iterator)
if iterator:
# Iterator is non-empty.
else:
# Iterator is empty.
Just beware if you kept refs to the old iterator, that iterator will get advanced. You have to use the new peekable iterator from then on. Really, though, peekable expects to be the only bit of code modifying that old iterator, so you shouldn't be keeping refs to the old iterator lying around anyway.