You can download this code by clicking the button below.
This code is now available for download.
The function combines multiple iterable objects into one, and fills in missing values with fillvalue if any iterable is exhausted.
Technology Stack : Built-in library (no additional packages)
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*args, fillvalue=None):
"""
Returns an iterator that aggregates elements from each of the iterables.
The iterator stops when the shortest iterable is exhausted, filling in missing values with fillvalue.
"""
iters = [iter(iterable) for iterable in args]
while True:
result = []
for it in iters:
try:
result.append(next(it))
except StopIteration:
result.append(fillvalue)
yield result