iterating "by twos"

castironpi castironpi at
Thu Aug 7 20:05:03 CEST 2008

On Jul 29, 3:38 pm, Terry Reedy <tjre... at> wrote:
> 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.

We note that three distinct methods of the mapping type protocol
support default, -or this if not found-, argument passing.

a.get(k[, x]) a[k] if k in a, else x (4)
a.setdefault(k[, x]) a[k] if k in a, else x (also setting it) (5)
a.pop(k[, x]) a[k] if k in a, else x (and remove k) (8)

You can knock off two of them with a default value:

itertools.igroup( iterable, groupsize[, dummy] )

Observe this overlap from the string type.

   find( sub[, start[, end]])
      Return the lowest index in the string where substring sub is
found, ...
      -1 if sub is not found.
   index( sub[, start[, end]])
      Like find(), but raise ValueError when the substring is not

Include two grouper functions, one that drops (or fills if 'dummy'
provided), one that returns (or fills if 'dummy' provided).

Or, include two grouper functions, one that drops (or fills), one that
raises ValueError exception, including the partial group as an
attribute of the exception.

If filling with 'None' is your concern, just use a special flag:

_special= object( )
iterb= itertools.grouper( itera, 2, _special )

More information about the Python-list mailing list