You can download this code by clicking the button below.
This code is now available for download.
This function behaves similarly to the built-in `zip` function, but will fill in missing values from the shorter iterables with `fillvalue` if they are exhausted.
Technology Stack : Built-in library
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*args, fillvalue=()):
"""
This function works like the built-in `zip` function, but will fill in missing values
from the shorter iterables with `fillvalue` if they are exhausted.
"""
iterators = [iter(arg) for arg in args]
longest = max(iterators, key=len)
for item in longest:
for i, it in enumerate(iterators):
try:
yield next(it)
except StopIteration:
yield fillvalue