You can download this code by clicking the button below.
This code is now available for download.
This function creates a new iterator that takes elements from multiple iterable objects, and if an element in one of the iterable objects is exhausted, it fills with the value specified by the fillvalue parameter.
Technology Stack : itertools, generators
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*args, fillvalue=0):
from itertools import zip_longest
def _zip_longest(*args, fillvalue=0):
iters = [iter(arg) for arg in args]
while True:
result = []
for it in iters:
try:
result.append(next(it))
except StopIteration:
result.append(fillvalue)
if len(result) == len(args):
return result
else:
iters = [iter(arg) for arg in args]
return _zip_longest(*args, fillvalue=fillvalue)