You can download this code by clicking the button below.
This code is now available for download.
Combines the elements of several iterable objects into a single iterable. If the shortest iterable is exhausted, missing values are filled with fillvalue.
Technology Stack : itertools, collections.abc
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*iterables, fillvalue=None):
"""
Zips the elements of several iterables together into a single iterable.
The iterables are treated as queues, and as soon as the shortest of the
iterables is exhausted, missing values are filled-in with fillvalue.
"""
from itertools import zip_longest as _zip_longest
from itertools import chain
import collections.abc
def is_iterable(obj):
try:
iter(obj)
return True
except TypeError:
return False
# Check if all provided arguments are iterable
for iterable in iterables:
if not is_iterable(iterable):
raise ValueError("All arguments must be iterable")
# Check if all provided arguments have the same length
lengths = [len(iterable) for iterable in iterables if hasattr(iterable, '__len__')]
if len(set(lengths)) > 1:
raise ValueError("All provided iterables must have the same length")
return _zip_longest(*iterables, fillvalue=fillvalue)