Iterating Over Unequal Length Iterables with FillValue

  • Share this:

Code introduction


Returns an iterator that aggregates elements from each of the iterables. If the iterables are of unequal length, missing values are filled with the fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


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

    Returns a new iterator aggregate elements from the given iterables. The iterator
    returns pairs, where the first element is taken from the first iterable and the
    second is taken from the second iterable, and so on. The returned pairs have the
    same length as the longest iterable. If an iterable is shorter than the others,
    missing values are filled-in with the fillvalue.

    Args:
        *iterables: An arbitrary number of iterables.
        fillvalue: The value to use for missing values if the iterables are of
            unequal length. Default is None.

    Returns:
        An iterator that aggregates elements from the given iterables.

    Examples:
        >>> list(zip_longest([1, 2, 3], ['a', 'b'], fillvalue='x'))
        [(1, 'a'), (2, 'b'), (3, 'x')]
        >>> list(zip_longest([1, 2, 3, 4], [0, 1], fillvalue=0))
        [(1, 0), (2, 1), (3, 0), (4, 0)]
    """
    # Implementation of the zip_longest function
    from itertools import zip_longest as it_zip_longest

    it = it_zip_longest(*iterables, fillvalue=fillvalue)
    while True:
        try:
            yield next(it)
        except StopIteration:
            break

# JSON representation of the function                
              
Tags: