Currently I\'m doing this:
try:
something = iterator.next()
# ...
except StopIteration:
# ...
But I would like an expression th
This isn't really cleaner, but it shows a way to package it in a function losslessly:
def has_elements(iter):
from itertools import tee
iter, any_check = tee(iter)
try:
any_check.next()
return True, iter
except StopIteration:
return False, iter
has_el, iter = has_elements(iter)
if has_el:
# not empty
This isn't really pythonic, and for particular cases, there are probably better (but less general) solutions, like the next default.
first = next(iter, None)
if first:
# Do something
This isn't general because None can be a valid element in many iterables.