[Python-ideas] Function to return first(or last) true value from list
אלעזר
elazarg at gmail.com
Thu Feb 20 14:11:59 CET 2014
2014-02-19 1:01 GMT+02:00 Steven D'Aprano <steve at pearwood.info>:
>
> On Tue, Feb 18, 2014 at 04:25:28PM -0600, Ryan Gonzalez wrote:
>
> > In Python 2, you'd do this:
> >
> > next((x for x in mylist if x))
>
> That works fine in Python 3 too.
>
The problem with this approach, which I personally ran into a couple of
days ago, is that raising StopIteration in the case of empty `mylist` is
*not* what you want, in general. "first" assumes non-exhausted iterator;
raising StopIteration is easily caught in the closest `for` loop, and you
end up failing silently. But
Errors should never pass silently.
This is a case of an "almost working" solution, similar to the and-or
"trenary" conditional operator. I think it's horrible. Non-advanced Python
programmer may not be able to find such a bug.
An implementation of first() should raise some other exception than
StopIteration.
Elazar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140220/a1b47ae6/attachment.html>
More information about the Python-ideas
mailing list