Zip Longest Iterator Function

  • Share this:

Code introduction


This function creates an iterator that aggregates elements from multiple iterable objects. It stops when the shortest iterable is exhausted and fills missing values with fillvalue.


Technology Stack : Built-in function

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "Make an iterator that aggregates elements from each of the iterables."
    "It stops when the shortest iterable is exhausted, filling missing values with fillvalue."
    iterators = [iter(it) for it in iterables]
    while True:
        result = []
        for it in iterators:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        if len(result) == 1:
            return result[0]
        yield result