[Python-ideas] Function to return first(or last) true value from list

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Feb 20 18:00:21 CET 2014


On 20 February 2014 16:34, Chris Angelico <rosuav at gmail.com> wrote:
> On Fri, Feb 21, 2014 at 3:14 AM, Oscar Benjamin
> <oscar.j.benjamin at gmail.com> wrote:
>> More-itertools does it the way I would but has a long comment
>> wondering whether it should actually raise StopIteration:
>> https://github.com/erikrose/more-itertools/blob/master/more_itertools/more.py#L37
>
> Has that been subsumed by next(iter(x),default) ?

If the default argument is provided then yes it's not giving much over
next/iter.

The effect that I more often want is that an empty iterable raises an
exception. next() with no default already does that but it's the wrong
kind of exception and can't safely be allowed to propagate. In that
case the alternative is

try:
    obj = next(iter(iterable))
except StopIteration:
    raise ValueError

(which is exactly what more-itertools first does).


Oscar


More information about the Python-ideas mailing list