[EMAIL PROTECTED] wrote:

On Jul 29, 1:36 pm, kj <[EMAIL PROTECTED]> 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 && [EMAIL PROTECTED] && 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
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to