iterating over two arrays in parallel?

Luis Zarrabeitia kyrie at uh.cu
Thu Aug 28 21:41:36 EDT 2008


Quoting mh at pixar.com:

> I want to interate over two arrays in parallel, something like this:
> 
>     a=[1,2,3]
>     b=[4,5,6]
> 
>     for i,j in a,b:
>         print i,j
> 
> where i,j would be 1,4,    2,5,   3,6  etc.
> 
> Is this possible?

Yeap.

===
for i,j in zip(a,b):
    print i,j
===

Or better yet (memory wise at least)

===
from itertools import izip

for i,j in izip(a,b):
    print i,j
===

("zip" creates a list with the pairs (i,j), izip returns an iterator over the
pairs "i,j")

> -- 
> Mark Harrison
> Pixar Animation Studios

Are you really from Pixar? Cool

Cheers,

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie




More information about the Python-list mailing list