What is the pythonic way to loop through two arrays at the same time?

If the lists a and b are short, use zip (as @Vincenzo Pii showed):

for x, y in zip(a, b):
    print(x + y)

If the lists a and b are long, then use itertools.izip to save memory:

import itertools as IT
for x, y in IT.izip(a, b):
    print(x + y)

zip creates a list of tuples. This can be burdensome (memory-wise) if a and b are large.

itertools.izip returns an iterator. The iterator does not generate the complete list of tuples; it only yields each item as it is requested by the for-loop. Thus it can save you some memory.

In Python2 calling zip(a,b) on short lists is quicker than using itertools.izip(a,b). But in Python3 note that zip returns an iterator by default (i.e. it is equivalent to itertools.izip in Python2).


Other variants of interest:

Leave a Comment