Merging Iterables with FillValue Support

  • Share this:

Code introduction


The function is used to merge multiple iterable objects into an iterator. If the lengths of some iterables are unequal, fillvalue is used to fill the shorter iterable.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    Return an iterator that aggregates elements from each of the iterables.

    The iterator returns pairs, where the first item is an index and the second item
    is the value obtained from the corresponding iterable. The returned index is
    the sum of the indices of the elements returned by the iterables. Once the
    shortest iterable is exhausted, missing values are filled-in with fillvalue.

    Example:
    >>> list(zip_longest('ABCD', 'xy', fillvalue='-'))
    [(0, 'A'), (1, 'x'), (2, 'B'), (3, 'y'), (4, '-')]
    """
    iters = [iter(it) for it in iterables]
    while True:
        result = []
        for idx, it in enumerate(iters):
            try:
                result.append((idx, next(it)))
            except StopIteration:
                iters[idx] = iter([fillvalue])
        yield result