On 20 February 2014 13:11, אלעזר <elazarg@gmail.com> wrote:
2014-02-19 1:01 GMT+02:00 Steven D'Aprano <steve@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.
I ran into this problem once some time ago and it took a long time to track down the bug. Since then a bare next with no default and no try/except StopIteration sticks out like a sore thumb every time I see it. Bare next() calls should be discouraged. In the situations where they are justified I think that it deserves a code comment at the least: x = next(iterator) # Propagate StopIteration Oscar