cdleary cdleary - 1 year ago 63
Python Question

Why is there no first(iterable) built-in function in Python?

I'm wondering if there's a reason that there's no

in the Python built-in functions, somewhat similar to
(it may be tucked in a stdlib module somewhere, but I don't see it in
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
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

match = first(regex.match(big_text) for regex in regexes)

You save a lot of unnecessary processing by avoiding
and short-circuiting on a positive match.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download