Python Language Iterating over generators in parallel


Example

To iterate over several generators in parallel, use the zip builtin:

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

Results in:

1 x
2 y
3 z

In python 2 you should use itertools.izip instead. Here we can also see that the all the zip functions yield tuples.

Note that zip will stop iterating as soon as one of the iterables runs out of items. If you'd like to iterate for as long as the longest iterable, use itertools.zip_longest().