iterating "by twos"

giltay at gmail.com giltay at gmail.com
Wed Jul 30 10:00:27 EDT 2008


On Jul 29, 4:11 pm, Erik Max Francis <m... at alcyone.com> wrote:
> gil... at gmail.com wrote:
> > for x, y in zip(a, a[1:]):
> >     frob(x, y)
>
> What you meant was this:
>
>  >>> [(x, y) for x, y in zip(a[::2], a[1::2])]
> [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
>
> but this creates three sublists through slicing and zip.  The use of
> islice and izip is better, particularly if the list that's being
> iterated over is large.

     The lists I use it with are generally pretty small (a few
thousand items at most) so I decided to go with simple rather than
clever.  That said, I use it enough that it should become its own
function, at which point I'll probably grab something from this
thread.

     Cheers,
Geoff G-T



More information about the Python-list mailing list