Python Implementation of itertools.zip_longest

  • Share this:

Code introduction


This function mimics the functionality of `itertools.zip_longest`. It uses `fillvalue` to pad shorter sequences when the lengths of the input sequences are not equal.


Technology Stack : Built-in functions, iterators, generators

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    from itertools import zip_longest as zip_longest_from_itertools

    def zip_longest_from_builtin(*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)
            yield result

    return zip_longest_from_builtin(*args, fillvalue=fillvalue)