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

Terry Reedy tjreedy at
Sun Sep 11 20:09:18 CEST 2011

On 9/11/2011 9:41 AM, Peter Otten wrote:
> 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
>     ...

In practice, I would use this rather than the loop above. However, I 
wanted to introduce the idea then used in the intermittent pairing of 

> (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
> that-all-iterables/
> that achieves near-C speed.

Interesting. It took a moment to see the general idea. For some reason, 
you timeit examples in the comment now all have "data = [range(1000)]3", 
missing '*'.

Terry Jan Reedy

More information about the Python-list mailing list