Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #13078

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

Path csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!feeder.news-service.com!newsfeed.xs4all.nl!newsfeed5.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail
Return-Path <python-python-list@m.gmane.org>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.000
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; 'else:': 0.03; 'instance,': 0.05; 'char': 0.07; 'desired.': 0.07; 'differently.': 0.07; 'raised': 0.07; 'received:verizon.net': 0.07; 'terry': 0.07; 'bits.': 0.09; 'first:': 0.09; 'loop.': 0.09; 'optionally': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:80.91.229.12': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'received:lo.gmane.org': 0.09; 'units.': 0.09; 'examples': 0.11; 'skip:[ 20': 0.12; 'protocol': 0.15; '*before*': 0.16; 'ahead.': 0.16; 'assignment.': 0.16; 'differently,': 0.16; 'incomplete': 0.16; 'iterator': 0.16; 'reedy': 0.16; 'surrogate': 0.16; 'lines,': 0.18; 'wrap': 0.18; 'jan': 0.19; 'implicit': 0.23; 'item.': 0.23; 'items.': 0.23; 'variable': 0.24; "python's": 0.24; 'times,': 0.24; 'code': 0.25; 'statement': 0.25; 'string': 0.26; 'posted': 0.26; 'raise': 0.28; 'skip:" 30': 0.28; 'explicitly': 0.29; 'generic': 0.29; 'odd': 0.29; 'yield': 0.29; 'second': 0.29; 'example': 0.30; 'binding': 0.30; 'iterating': 0.30; 'separately.': 0.30; 'situations': 0.30; 'least': 0.31; 'version': 0.32; 'list': 0.32; 'there': 0.33; 'to:addr:python-list': 0.33; 'copying': 0.33; 'points': 0.34; 'done': 0.34; 'header:User-Agent:1': 0.34; 'explicit': 0.34; 'flag': 0.34; 'subject:next': 0.34; 'try:': 0.34; 'header:X -Complaints-To:1': 0.35; 'rather': 0.35; 'useful': 0.36; 'skip:" 10': 0.36; 'pull': 0.37; 'rest': 0.37; 'several': 0.37; 'received:org': 0.38; 'allows': 0.38; 'characters': 0.39; 'header :Mime-Version:1': 0.39; 'empty': 0.39; 'to:addr:python.org': 0.39; 'case': 0.39; 'full': 0.63; 'manner': 0.64; 'harder': 0.64; 'traditional': 0.64; 'here': 0.65; '"for': 0.67; '(unicode)': 0.84; '(while': 0.84; 'idiom': 0.84; 'penalty,': 0.84; 'items,': 0.91
X-Injected-Via-Gmane http://gmane.org/
To python-list@python.org
From Terry Reedy <tjreedy@udel.edu>
Subject Idioms combining 'next(items)' and 'for item in items:'
Date Sat, 10 Sep 2011 15:36:42 -0400
Mime-Version 1.0
Content-Type text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding 7bit
X-Gmane-NNTP-Posting-Host pool-74-109-121-73.phlapa.fios.verizon.net
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20110812 Thunderbird/6.0
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.12
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <http://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.944.1315683474.27778.python-list@python.org> (permalink)
Lines 97
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1315683474 news.xs4all.nl 2442 [2001:888:2000:d::a6]:47854
X-Complaints-To abuse@xs4all.nl
Xref x330-a1.tempe.blueboxinc.net comp.lang.python:13078

Show key headers only | View raw


Python's iterator protocol for an iterator 'items' allows combinations 
of explicit "next(items)" calls with the implicit calls of a "for item 
in items:" loop. There are at least three situations in which this can 
be useful. (While the code posted here is not testable, being incomplete 
or having pseudocode lines, I have tested full examples of each idiom 
with 3.2.)


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>

Sometimes <other setup> and <process first> can be combined in <setup 
with next(items)>. For instance, "result = []" followed by 
"result.append(process_first(item))" becomes "result = 
[process_first(item)]".

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")


For an iterable known to have a small number of items, the first item 
can be removed, with only a small copying penalty, with a simple assignment.

first, *rest = iterable

The older and harder to write version of this requires the iterable to 
be a sequence?

first, rest = seq[0], seq[1:]


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.

items = iter(iterable)
current = next(items)
for item in items:
   <process non-last current>
   current = item
<process last current>

To treat both first and last differently, pull off the first before 
binding 'current'. Wrap next() calls as desired.


3. Process the items of an iterable in pairs.

items = iter(iterable)
for first in items:
     second = next(items)
     <process first and second>

This time, StopIteration is raised for an odd number of items. Catch and 
process as desired. One possibility is to raise ValueError("Iterable 
must have an even number of items").

A useful example of just sometimes pairing is iterating a (unicode) 
string by code points ('characters') rather than by code units. This 
requires combining the surrogate pairs used for supplementary characters 
when the units are 16 bits.

chars = iter(string)
for char in chars:
     if is_first_surrogate(char):
         char += next(chars)
     yield char

-- 
Terry Jan Reedy

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Idioms combining 'next(items)' and 'for item in items:' Terry Reedy <tjreedy@udel.edu> - 2011-09-10 15:36 -0400
  Re: Idioms combining 'next(items)' and 'for item in items:' Duncan Booth <duncan.booth@invalid.invalid> - 2011-09-12 13:06 +0000
    Re: Idioms combining 'next(items)' and 'for item in items:' Terry Reedy <tjreedy@udel.edu> - 2011-09-12 15:24 -0400

csiph-web