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

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Feb 20 17:14:17 CET 2014


On 20 February 2014 16:05, Terry Reedy <tjreedy at udel.edu> wrote:
>>
>> An implementation of first() should raise some other exception than
>> StopIteration.
>
>
> #untested
> __missing = object()
> def first(iterable, default=__missing):
>   for o in interable:
>     if o:
>       return o
>   else:
>     if default is not __missing:
>       return default
>     else:
>       raise ValueError("iterable has no true value and there is no default")

It's easy enough to do if you know that bare next is a bad thing.
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

The thing is just that bare next is not something that's widely
recognised as being dangerous. I've seen examples of this kind of bug
in samples from many Python aficionados (including at least one from
you Terry).


Oscar


More information about the Python-ideas mailing list