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


Groups > comp.lang.python > #13126 > unrolled thread

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

Started byPeter Otten <__peter__@web.de>
First post2011-09-11 15:41 +0200
Last post2011-09-11 15:41 +0200
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Idioms combining 'next(items)' and 'for item in items:' Peter Otten <__peter__@web.de> - 2011-09-11 15:41 +0200

#13126 — Re: Idioms combining 'next(items)' and 'for item in items:'

FromPeter Otten <__peter__@web.de>
Date2011-09-11 15:41 +0200
SubjectRe: Idioms combining 'next(items)' and 'for item in items:'
Message-ID<mailman.988.1315748478.27778.python-list@python.org>
Terry Reedy wrote:

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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web