Combining Iterables with Variable Lengths

  • Share this:

Code introduction


This function combines multiple iterables of different lengths. If an iterable ends prematurely, it fills in the missing parts with a fillvalue.


Technology Stack : itertools, zip_longest, islice, map, iter, next

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    Zip together multiple iterables (sequences) but allow each iterable to be of a different length.
    Return an iterator that aggregates elements from each of the iterables. The iterator returns pairs of elements
    from each iterable as they come, until the shortest iterable is exhausted. Then, it fills in with fillvalue.

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

    def iter_from_iterable(iterable):
        iterator = iter(iterable)
        while True:
            yield next(iterator, fillvalue)

    return zip_longest(*map(iter_from_iterable, iterables))