iterating "by twos"

shahms.king at gmail.com shahms.king at gmail.com
Thu Aug 7 11:06:12 EDT 2008


On Jul 29, 10:36 am, 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 mean, other than
>
> for i in range(0, len(a), 2):
>     frobnicate(a[i], a[i+1])
>
> ?
>
> I think I once saw something like
>
> for (x, y) in forgotten_expression_using(a):
>     frobnicate(x, y)
>
> Or maybe I just dreamt it!  :)
>
> Thanks!
> --
> NOTE: In my address everything before the first period is backwards;
> and the last period, and everything after it, should be discarded.

This avoids unnecessary copies of the slice approaches, it does,
however, not include the tail values if the length of iterable isn't
evenly divisible by 'size'.

def groups(iterable, size=2):
  return itertools.izip(*[iter(iterable)]*size)

print list(groups(xrange(5)))

[(0, 1), (1, 2), (3, 4)]

--Shahms



More information about the Python-list mailing list