Extended Zip Function with Fillvalues

  • Share this:

Code introduction


This function is similar to the built-in zip() function, but it fills the shortest input iterable with fillvalues from the next input iterables until all of the input iterables are exhausted.


Technology Stack : Iterator, generator

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Like zip(), but the shortest input iterable is extended by fillvalues from the next
    input iterables until all of the input iterables are exhausted.

    :param *args: Variable length argument list. Each argument is an iterable.
    :param fillvalue: Value to use for missing values in the shorter iterables.
    :return: An iterator that aggregates elements from each of the iterables.
    """
    iterators = [iter(arg) for arg in args]
    while True:
        result = []
        for it in iterators:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        if len(result) == len(args):
            yield result
        else:
            break