Custom Fillvalue Zip Function

  • Share this:

Code introduction


This function implements functionality similar to the built-in zip function but allows you to specify a fill value to fill in missing values from iterables of different lengths.


Technology Stack : itertools.zip_longest, itertools.islice

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    Like zip() but fills in missing values from the iterables with fillvalue.

    :param *iterables: An arbitrary number of iterables.
    :param fillvalue: The value to use for missing values.
    :return: An iterator that aggregates elements from each of the iterables.
    """
    from itertools import zip_longest
    from itertools import islice

    def fill_missing(iterable, fillvalue):
        return (x if i < len(iterable) else fillvalue for i, x in enumerate(iterable))

    zipped = zip_longest(*iterables, fillvalue=fillvalue)
    for i, x in enumerate(zipped):
        if fillvalue is not None:
            iterables[i] = fill_missing(iterables[i], fillvalue)
        yield x