Combining Iterables with Fillvalue

  • Share this:

Code introduction


This function is used to combine multiple iterables of different lengths. If an iterable is shorter than the others, the missing values are filled with a specified fill value.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """Zip equal length sequences together, but allow extra values from longer sequences.
    
    Parameters:
    *args: An arbitrary number of sequences.
    fillvalue: Value to use for missing values from shorter sequences.
    
    Returns:
    An iterator that aggregates elements from each of the iterables.
    The iterator stops when the shortest iterable is exhausted, even if the longer iterables still have elements left.
    """
    iters = [iter(iterable) for iterable in args]
    while True:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        yield tuple(result)