Extending Zip Function for Irregularly Sized Iterables

  • Share this:

Code introduction


The function extends the zip function to allow iteration over iterables of different lengths. It fills in missing values with the specified fillvalue.


Technology Stack : Built-in function zip, iterators

Code Type : Iterator

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    This function extends the zip function to allow iteration over an irregularly
    sized iterable. It fills in missing values with the fillvalue.

    :param args: An arbitrary number of iterables.
    :param fillvalue: The value to use for missing values.
    :return: An iterator that aggregates elements from each of the iterables.
    """
    iterators = [iter(iterable) for iterable in args]
    while True:
        for i, it in enumerate(iterators):
            try:
                iterators[i] = next(it)
            except StopIteration:
                iterators[i] = fillvalue
                yield fillvalue
        yield tuple(iterators)