Creating a Zip Longest Function in Python

  • Share this:

Code introduction


This function is used to merge multiple iterable objects into an iterator. If the lengths of the iterable objects are not consistent, fillvalue is used to fill the missing parts.


Technology Stack : Built-in function

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    iters = [iter(arg) for arg in args]
    while True:
        result = []
        for iter_ in iters:
            try:
                result.append(next(iter_))
            except StopIteration:
                result.append(fillvalue)
        if not any(result):
            break
        yield tuple(result)