Iterating over generators in parallel

suggest change

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

a = [1, 2, 3]
b = ['x', 'y', 'z']
for x, y in zip(a, b):
    print(x, y)

Results in:

1 x
2 y
3 z

Note that zip stops as soon as one of the iterables runs out of items. To continue until the longest iterable is exhausted, use itertools.zip_longest().

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents