Zipping two iterators until they are both exhausted

suggest change

Similar to the built-in function zip(), itertools.zip_longest will continue iterating beyond the end of the shorter of two iterables.

from itertools import zip_longest
a = [i for i in range(5)] # Length is 5
b = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] # Length is 7
for i in zip_longest(a, b):
    x, y = i  # Note that zip longest returns the values as a tuple
    print(x, y)

An optional fillvalue argument can be passed (defaults to '') like so:

for i in zip_longest(a, b, fillvalue='Hogwash!'):
    x, y = i  # Note that zip longest returns the values as a tuple
    print(x, y)

In Python 2.6 and 2.7, this function is called itertools.izip_longest.

Feedback about page:

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



Table Of Contents