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

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Feb 21 16:44:54 CET 2014


On 21 February 2014 09:25, Peter Otten <__peter__ at web.de> wrote:
>>>
>>> It is *very* similar to the "and or" story.
>
> I think the difference is that once you've learned the lesson you stop using
> `and...or` while you change your usage pattern for next() to minimal scopes
>
> def process_source(source):
>     it = iter(source)
>     first = next(it)
>     for item in it:
>         yield first * item
>
> def itermerge(sources):
>     for source in sources:
>         yield from process_source(source)

Maybe but is it really correct to just ignore that empty iterable?
When I use sequences and write first = seq[0] I'm deliberately
asserting that seq is non-empty. I want to see a traceback if for
whatever reason it should turn out to be an empty sequence. Using
next() and allowing the StopIteration to terminate what you're doing
assumes that it's okay to just ignore an empty iterable and go do
something else.

Leaking StopIteration may be a conscious decision but it's not clear
when looking at first = next(it) whether it is. In my own code I would
put a comment there to indicate that I have considered the implication
and decided that it's okay (and then when I see a bare next with no
comment it instantly arouses suspicion).


Oscar


More information about the Python-ideas mailing list