This is not very clean, but it shows a way to batch convert to a lossless function:
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:
This is not really pythonic, and for some cases there are probably better (but less general) solutions, such as next by default.
first = next(iter, None) if first:
This is not common, because None can be a valid element in many iterations.
Matthew Flaschen Jun 24 2018-10-10T00: 00Z
source share