I'm wondering if there's a reason that there's no first(iterable)
in the Python built-in functions, somewhat similar to any(iterable)
and all(iterable)
(it may be tucked in a stdlib module somewhere, but I don't see it in itertools
). first
would perform a short-circuit generator evaluation so that unnecessary (and a potentially infinite number of) operations can be avoided; i.e.
def identity(item):
return item
def first(iterable, predicate=identity):
for item in iterable:
if predicate(item):
return item
raise ValueError('No satisfactory value found')
This way you can express things like:
denominators = (2, 3, 4, 5)
lcd = first(i for i in itertools.count(1)
if all(i % denominators == 0 for denominator in denominators))
Clearly you can't do list(generator)[0]
in that case, since the generator doesn't terminate.
Or if you have a bunch of regexes to match against (useful when they all have the same groupdict
interface):
match = first(regex.match(big_text) for regex in regexes)
You save a lot of unnecessary processing by avoiding list(generator)[0]
and short-circuiting on a positive match.
If you have an iterator, you can just call its next
method. Something like:
In [3]: (5*x for x in xrange(2,4)).next()
Out[3]: 10