Aggregating Iterables with Fillvalue Support

  • Share this:

Code introduction


This function is used to concatenate multiple iterable objects. If they are of uneven length, fillvalue is used to fill in missing values.


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.

    If the iterables are of uneven length, missing values are filled-in with
    fillvalue. Default is None.

    Args:
        *iterables: An arbitrary number of iterables.
        fillvalue: Value to use for missing values if the iterables are of uneven length.

    Returns:
        An iterator that aggregates elements from each of the iterables.

    Examples:
        >>> list(zip_longest([1, 2, 3], [4, 5], fillvalue=0))
        [1, 4, 2, 5, 3, 0]
        >>> list(zip_longest([1, 2, 3], [4, 5], [6, 7], fillvalue=-1))
        [1, 4, 6, 2, 5, 7, 3, -1]
    """
    iterators = [iter(it) for it in iterables]
    while True:
        result = []
        for it in iterators:
            try:
                result.append(next(it))
            except StopIteration:
                iterators.remove(it)
                result.append(fillvalue)
        if len(result) == 1 and result[0] == fillvalue:
            break
        yield result