You can download this code by clicking the button below.
This code is now available for download.
This function provides similar functionality to the built-in `zip_longest`, but uses `collections.deque` for optimization.
Technology Stack : collections.deque, itertools.zip_longest
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*args, fillvalue=None):
"""
Like zip(), but the shortest input iterable is extended by fillvalue.
"""
from itertools import zip_longest
from collections import deque
def fill_iter(fillvalue):
while True:
yield fillvalue
iterators = [deque(iter(i)) for i in args]
while iterators:
result = []
for it in iterators:
try:
result.append(next(it))
except StopIteration:
iterators.remove(it)
if not iterators:
break
yield tuple(result)
if fillvalue is not None:
iterators.extend(fill_iter(fillvalue))