Combining Iterables with Fillvalue

  • Share this:

Code introduction


Combine multiple iterable objects into one, filling in missing values with a specified fill value if one of the iterables ends prematurely.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """Combine several iterables (zip_longest) and fill in missing values with a specified fillvalue.

    Args:
        *args: Variable number of iterables to be zipped together.
        fillvalue: Value to use for missing values in the shorter iterables.

    Returns:
        An iterator that aggregates elements from each of the iterables.
        Returns the next value from each iterable as long as they all have values.
        When the shortest iterable is exhausted, fills in missing values with the fillvalue.

    Example:
        >>> list(zip_longest([1, 2, 3], [4, 5], [6], fillvalue=-1))
        [(1, 4, 6), (2, 5, -1), (3, -1, -1)]

    """
    from itertools import zip_longest as _zip_longest
    return _zip_longest(*args, fillvalue=fillvalue)                
              
Tags: