zip_longest: Aggregating Elements with Fill Values

  • Share this:

Code introduction


The function takes multiple iterable objects as arguments and returns an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled in with a specified fill value.


Technology Stack : The function takes multiple iterable objects as arguments and returns an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled in with a specified fill value.

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "Make an iterator that aggregates elements from each of the iterables.
    If the iterables are of uneven length, missing values are filled-in with fillvalue.
    Parameters
    ----------
    iterables : sequence or iterator
        An iterable sequence of iterables.
    fillvalue : object
        The value to use for missing values if the iterables are of uneven length.
    Examples
    --------
    >>> from itertools import zip_longest
    >>> list(zip_longest([1, 2, 3], 'abc', fillvalue='-'))
    [(1, 'a', '-'), (2, 'b', '-'), (3, 'c', '-')]
    >>> list(zip_longest('abc', '12345678901234567890', fillvalue='x'))
    [('a', '1'), ('b', '2'), ('c', '3'), ('x', '4'), ('x', '5'), ('x', '6'), ('x', '7'), ('x', '8'), ('x', '9'), ('x', '10'), ('x', '11'), ('x', '12'), ('x', '13'), ('x', '14'), ('x', '15')]
    """
    # zip_longest uses zip_longest from itertools package
    from itertools import zip_longest

    # Define the function
    def zip_longest_generator(*args):
        iters = iterables
        for i in zip_longest(*iters, fillvalue=fillvalue):
            yield i

    # Convert the generator to a list to simulate a function call
    return list(zip_longest_generator(*iterables))