Idioms combining 'next(items)' and 'for item in items:'

Terry Reedy tjreedy at udel.edu
Mon Sep 12 15:24:14 EDT 2011


On 9/12/2011 9:06 AM, Duncan Booth wrote:
> 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,

To do nothing, just pass above. If the function does nothing, it returns 
None. In the fix_title function, it should return '', not None.

> you could write it like this:
>
>      items = iter(iterable)
>      for first in items:
>          <process first>
>          break

I could, but I doubt I would ;-). Try...except StopIteration: pass is 
more explicit and less roundabout.

>      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,

Likely? I would say occasionally. Sentences have first words; file have 
headers. Special processing for last items is only an issue if it 
*replaces* the normal processing, rather than following the normal 
processing.

 > 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.

Like so, with tests:

def first_last_special(iterable):
     print("\nIterable is",repr(iterable))
     items = iter(iterable)
     try:
         first = next(items)
     except StopIteration:
         print('Nothing'); return
     print(first, 'is the first item')
     try:
         current = next(items)
     except StopIteration:
         current = first
     else:
         for item in items:
             print(current, 'is a middle item')
             current = item
     print(current, 'is the last item')

first_last_special('')
first_last_special('1')
first_last_special('12')
first_last_special('123')
first_last_special('12345')

-- 
Terry Jan Reedy




More information about the Python-list mailing list