Creating a Zip Longest Iterator in Python

  • Share this:

Code introduction


This function creates an iterator that aggregates elements from multiple iterable objects. If the iterables are of unequal length, fillvalue is used to fill in missing values.


Technology Stack : Iterator, generator, exception handling

Code Type : Iterator

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "Make an iterator that aggregates elements from each of the iterables.
    The iterables must be of the same length or None, and the iterator
    stops when the shortest iterable is exhausted. Fillvalue is used for
    missing values if the iterables are of unequal length."
    iterators = [iter(it) for it in iterables]
    while True:
        result = []
        for it in iterators:
            try:
                result.append(next(it))
            except StopIteration:
                iterators.remove(it)
                if not iterators:
                    return
                result.append(fillvalue)
        yield result