Combining Iterables with FillValue Using zip_longest

  • Share this:

Code introduction


The zip_longest function combines multiple iterable objects (such as lists, tuples, etc.) into an iterator. If the iterables have different lengths, it uses a specified fill value to fill in the shorter ones.


Technology Stack : zip_longest

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # This function zips multiple iterables (lists, tuples, etc.) together, 
    # filling in missing values with a specified fillvalue if the iterables are of unequal length.
    
    # Python's zip function stops creating pairs when the shortest iterable is exhausted.
    # zip_longest extends this behavior to allow for a specified fillvalue for shorter iterables.
    
    iterators = [iter(it) for it in iterables]
    while True:
        result = []
        for it in iterators:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        yield tuple(result)                
              
Tags: