iterating "by twos"

william tanksley wtanksleyjr at gmail.com
Tue Jul 29 15:42:07 EDT 2008


kj <so... at 987jk.com.invalid> wrote:
> Is there a special pythonic idiom for iterating over a list (or
> tuple) two elements at a time?

I don't know of one, and I shouldn't be answering, but the following
should work:

def gulp_two(items):
  for i,j in zip(items[0::2], items[1::2]):
    yield (i,j)

Let's see...
>>> list(gulp_two(range(10)))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

Okay, it works.

-Wm



More information about the Python-list mailing list