Python Custom Zip_longest Function Mimicking Built-in Behavior

  • Share this:

Code introduction


This function mimics the built-in zip_longest function. It fills in missing values with fillvalue when the lengths of the iterators are inconsistent.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest

    def my_zip_longest(*iterables, fillvalue=None):
        iterator = zip_longest(*iterables, fillvalue=fillvalue)
        for iterable in iterables:
            for element in iterable:
                yield element
        for fill_value in fillvalue:
            yield fill_value

    return my_zip_longest(*args, fillvalue=fillvalue)                
              
Tags: