You can download this code by clicking the button below.
This code is now available for download.
The function takes multiple iterable objects as arguments, combines them into tuples, and if any iterable is exhausted, it fills the remaining tuples with `fillvalue`.
Technology Stack : Built-in functions
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*args, fillvalue=None):
"""
This function is similar to the built-in `zip` function, but it allows the iteration to be
continued until the longest input sequence is exhausted. If the sequences are of unequal
lengths, missing values are filled in with `fillvalue`.
"""
iterators = [iter(arg) for arg in args]
while True:
result = []
for iterator in iterators:
try:
result.append(next(iterator))
except StopIteration:
result.append(fillvalue)
if len(result) == 0:
break
yield tuple(result)
# JSON output