iterating "by twos"
giltay at gmail.com
giltay at gmail.com
Tue Jul 29 15:42:19 EDT 2008
On Jul 29, 2:36 pm, gil... at gmail.com wrote:
> On Jul 29, 1:36 pm, 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 use this one a lot:
>
> for x, y in zip(a, a[1:]):
> frob(x, y)
>
> Geoff G-T
Whoops, I misread the original post. That would be:
for x, y in zip(a[::2], a[1::2]):
frob(x, y)
... which I don't use a lot.
>>> a = range(9)
>>> for x, y in zip(a, a[1:]):
... print x, y
...
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
>>> for x, y in zip(a[::2], a[1::2]):
... print x, y
...
0 1
2 3
4 5
6 7
Geoff G-T
More information about the Python-list
mailing list