Idioms combining 'next(items)' and 'for item in items:'
Duncan Booth
duncan.booth at invalid.invalid
Mon Sep 12 09:06:47 EDT 2011
Terry Reedy <tjreedy at udel.edu> wrote:
> The statement containing the explicit next(items) call can optionally be
> wrapped to explicitly handle the case of an empty iterable in whatever
> manner is desired.
>
> try:
> <set up with next(items)>
> except StopIteration:
> raise ValueError("iterable cannot be empty")
>
>
Alternatively, if all you want is for an empty iterable to do nothing, you
could write it like this:
items = iter(iterable)
for first in items:
<process first>
break
for item in items:
<process non-first>
However, the issue I have with any of this pulling the first element out of
the loop is that if you want special processing for the first element you
are likely to also want it for the last, and if it is a single item you need
to process that item with both bits of special code. I don't see how that works
unless you have all elements within the single loop and test for first/last.
> 2. Process the last item of an iterable differently. As far as I know,
> this cannot be done for a generic iterable with a flag. It requires a
> look ahead.
I think that must be correct, e.g. if reading from an interactive prompt you
cannot detect end of input until you fail to read any more.
See my answer to http://stackoverflow.com/questions/7365372/is-there-a-pythonic-way-of-knowing-when-the-first-and-last-loop-in-a-for-is-being/7365552#7365552
for a generator that wraps the lookahead.
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list