Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!gegeweb.org!de-l.enfer-du-nord.net!feeder1.enfer-du-nord.net!feeder.news-service.com!news2.euro.net!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail Return-Path: 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; 'desired.': 0.07; 'raised': 0.07; 'terry': 0.07; '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; 'recipe': 0.09; 'silently': 0.09; 'url:activestate': 0.09; 'exception': 0.12; 'received:dip.t-dialin.net': 0.16; 'received:t-dialin.net': 0.16; 'reedy': 0.16; 'written': 0.16; 'wrote:': 0.16; '2.x': 0.18; 'url:code': 0.23; '(b)': 0.23; 'items.': 0.23; 'raise': 0.28; 'odd': 0.29; 'second': 0.29; 'from:addr:web.de': 0.30; 'ago': 0.31; 'there': 0.33; 'to:addr:python-list': 0.33; "i've": 0.34; '...': 0.34; '(a)': 0.34; 'subject:next': 0.34; 'header:X -Complaints-To:1': 0.35; 'another': 0.37; 'but': 0.37; 'received:org': 0.38; 'some': 0.38; 'subject:: ': 0.39; 'header :Mime-Version:1': 0.39; 'to:addr:python.org': 0.39 X-Injected-Via-Gmane: http://gmane.org/ To: python-list@python.org From: Peter Otten <__peter__@web.de> Subject: Re: Idioms combining 'next(items)' and 'for item in items:' Date: Sun, 11 Sep 2011 15:41:23 +0200 Organization: None References: Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Gmane-NNTP-Posting-Host: p5084aa93.dip.t-dialin.net X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.12 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 36 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1315748478 news.xs4all.nl 2487 [2001:888:2000:d::a6]:35856 X-Complaints-To: abuse@xs4all.nl Xref: x330-a1.tempe.blueboxinc.net comp.lang.python:13126 Terry Reedy wrote: > 3. Process the items of an iterable in pairs. > > items = iter(iterable) > for first in items: > second = next(items) > > > 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"). Another way is zip-based iteration: (a) silently drop the odd item items = iter(iterable) for first, second in zip(items, items): # itertools.izip in 2.x ... (b) add a fill value for first, second in itertools.zip_longest(items, items): ... (c) raise an exception Unfortunately there is no zip_exc() that guarantees that all iterables are of the same "length", but I've written a recipe some time ago http://code.activestate.com/recipes/497006-zip_exc-a-lazy-zip-that-ensures- that-all-iterables/ that achieves near-C speed.