The next
function is useful even without iterating. Passing a generator expression to next
is a quick way to search for the first occurrence of an element matching some predicate. Procedural code like
def find_and_transform(sequence, predicate, func):
for element in sequence:
if predicate(element):
return func(element)
raise ValueError
item = find_and_transform(my_sequence, my_predicate, my_func)
can be replaced with:
item = next(my_func(x) for x in my_sequence if my_predicate(x))
# StopIteration will be raised if there are no matches; this exception can
# be caught and transformed, if desired.
For this purpose, it may be desirable to create an alias, such as first = next
, or a wrapper function to convert the exception:
def first(generator):
try:
return next(generator)
except StopIteration:
raise ValueError