Zip Longest with Fillvalue

  • Share this:

Code introduction


The function zips together multiple iterable objects into an iterator, filling in missing values with the specified fillvalue if one of the iterables ends first.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # This function will zip together multiple iterables, filling in 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 not result:
            break
        yield tuple(result)

# Code Information