iterating "by twos"

Erik Max Francis max at alcyone.com
Tue Jul 29 16:11:57 EDT 2008


giltay 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)

It doesn't work:

 >>> a = range(10)
 >>> [(x, y) for x, y in zip(a, a[1:])]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]

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.

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
   Tell me the truth / I'll take it like a man
    -- Chante Moore



More information about the Python-list mailing list