Zip Longest Function for Iterables

  • Share this:

Code introduction


The function is used to merge multiple iterable objects (such as lists, tuples, etc.) into an iterator. If the length of the iterable objects is different, the specified fill value is used to fill in the missing parts.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    from itertools import zip_longest
    # This function zips together multiple iterables (lists, tuples, etc.) and fills in missing values with a specified fill value.
    # If the iterables are of unequal length, missing values are filled in with the fillvalue.
    
    zipped = zip_longest(*iterables, fillvalue=fillvalue)
    for item in zipped:
        if fillvalue is not None and fillvalue in item:
            item = list(item)
            item[item.index(fillvalue)] = None
            item = tuple(item)
        yield item

# JSON representation                
              
Tags: