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

Tim Chase python.list at tim.thechases.com
Sun Sep 11 08:41:58 EDT 2011


On 09/10/11 14:36, Terry Reedy wrote:
> 1. Process first item of an iterable separately.
>
> A traditional solution is a flag variable that is tested for each item.
>
> first = True
> <other setup>
> for item in iterable:
>     if first:
>       <process first>
>       first = False
>     else:
>       <process non-first>
>
> (I have seen code like this posted on this list several times, including
> today.)
>
> Better, to me, is to remove the first item *before* the loop.
>
> items = iter(iterable)
> <set up with next(items)
> for item in items:
>     <process non-first>

I like to use this one for processing CSV files where I need to 
clean up the headers:

   r = csv.reader(f)
   headers = r.next()
   header_map = dict(
     (header.strip().upper(), i)
     for i, header
     in enumerate(headers)
     )
   for row in r:
     item = lambda s: row[header_map[s]].strip()
     thing = item("THING")
     whatever = item("WHATEVER")

It's mostly like a DictReader, but it isn't as sensitive to the 
spaces/capitalization that clients love to mess with.

-tkc






More information about the Python-list mailing list