Combining Iterables with Fillvalue for Inconsistent Lengths

  • Share this:

Code introduction


This function is used to combine multiple iterable objects, and fill missing parts with a specified fill value if the lengths of the iterable objects are not consistent.


Technology Stack : itertools.zip_longest, itertools.islice

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Zip together multiple iterables but allow None values for missing values from the iterables.
    """
    from itertools import zip_longest
    from itertools import islice

    zipped = zip_longest(*args, fillvalue=fillvalue)
    for i in range(len(zipped)):
        for j in range(len(zipped[i])):
            if zipped[i][j] is None:
                zipped[i][j] = fillvalue
    return zipped