Iterating two arrays at once

Matthias Bläsing matthias.blaesing at rwth-aachen.de
Fri Aug 29 06:46:05 EDT 2008


Am Fri, 29 Aug 2008 03:35:51 -0700 schrieb mathieu:> 
>   A = [1,2,3]
>   B = [4,5,6]
>   for a,b in A,B: # does not work !
>     print a,b
> 
> It should print:
> 
>   1,4
>   2,5
>   3,6

Hey,

zip is your friend:

for a,b in zip(A,B):
	print a,b

does what you want. If you deal with big lists, you can use izip from 
itertools, which returns a generator.

from itertools import izip
for a,b in izip(A,B):
	print a,b

HTH

Matthias



More information about the Python-list mailing list