You can download this code by clicking the button below.
This code is now available for download.
This function combines multiple iterable objects into a tuple. If one of the iterable objects is longer than the others, it fills the remaining positions with `fillvalue`.
Technology Stack : Built-in libraries
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*args, fillvalue=None):
"""
This function is similar to the built-in `zip` function, but it will fill missing values
from the shorter iterables with `fillvalue` until the longest iterable is exhausted.
"""
iterators = [iter(arg) for arg in args]
longest = max(iterators, key=len)
for element in longest:
for iterator in iterators:
try:
yield next(iterator)
except StopIteration:
yield fillvalue