iterating "by twos"

Terry Reedy tjreedy at udel.edu
Tue Jul 29 16:38:53 EDT 2008



kj wrote:

> Is there a special pythonic idiom for iterating over a list (or
> tuple) two elements at a time?
> 
> I mean, other than
> 
> for i in range(0, len(a), 2):
>     frobnicate(a[i], a[i+1])

There have been requests to add a grouper function to itertools, but its 
author has resisted because there are at least three things one might do 
with the short remainder group left over when the group size does not 
evenly divide the sequence size: drop it, return it, or fill it to the 
requested groupsize with a dummy value and then return it.  Here is a 
version of the first alternative.

def grouper(iterable,n):
     '''Return items from iterable in groups of n.
        This version drops incomplete groups.
        Python 3.0'''

     it=iter(iterable)
     ranger = range(n)
     while True:
         ret = []
         for i in ranger:
             ret.append(next(it))
         yield ret

for pair in grouper(range(11),2):
     print(pair)

[0, 1]
[2, 3]
[4, 5]
[6, 7]
[8, 9]
 >>>




More information about the Python-list mailing list