Zip Longest Function with Fillvalue

  • Share this:

Code introduction


The function returns an iterator that merges multiple iterable objects into one iterator. If the iterable objects are of unequal lengths, it fills the shorter ones with a specified fill value.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # This function is similar to zip(), but the iterator(s) shorter than the longest one will be filled with a specified value.

    # Iterate over each iterable and pair it with the fillvalue if it's exhausted.
    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 not result:
            break
        yield tuple(result)