Zip Longest with Fillvalue for Iterables

  • Share this:

Code introduction


This function takes multiple iterable objects (like lists, strings, etc.) and returns a zip object that aggregates elements from each of the iterables. If the iterables are of unequal length, missing values are filled in with `fillvalue`.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    Take multiple iterables (lists, strings, etc.) and return a zip object
    that aggregates elements from each of the iterables. If the iterables are
    of unequal length, missing values are filled-in with `fillvalue`.
    """
    from itertools import zip_longest
    from collections import defaultdict

    def aggregate(values):
        for value in values:
            if isinstance(value, list):
                for item in value:
                    yield item
            else:
                yield value

    zipped = zip_longest(*args, fillvalue=fillvalue)
    aggregated = aggregate(zipped)
    return list(aggregated)