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

Peter Otten __peter__ at
Sun Sep 11 15:41:23 CEST 2011

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

that achieves near-C speed.

More information about the Python-list mailing list