[Tutor] Iterate by twos

Kent Johnson kent37 at tds.net
Sun Nov 2 22:02:02 CET 2008


On Sun, Nov 2, 2008 at 3:53 PM, W W <srilyk at gmail.com> wrote:
> is there a better/more pythonic way to do something like this?
>
> spam = ['c','c','v','c','v']
>
> for x in xrange(0,5,2):
>     print spam[x], spam[x+1]

You could use this function (from the itertools recipes):
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

This problem has many solutions. It is a perennial on comp.lang.python
and in the Python Cookbook, perhaps because none of the solutions is
compellingly better than the rest. They also vary depending on how
they handle missing values in the last group. Here is a thread on
comp.lang.python with some ideas:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/4696a3b3e1a6d691/

But really, what you did is fine. Here is a simple generator for pairs
that returns a short pair if len(seq) is odd:
def pairs(seq):
  for i in xrange(0, len(seq), 2):
    yield seq[i:i+2]

Kent


More information about the Tutor mailing list