Handling Multiple Iterables with zip_longest

  • Share this:

Code introduction


This function uses the zip_longest function from the itertools library to handle multiple iterable objects. If one of the iterable objects is exhausted first, fillvalue is used to fill in.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


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

    def iterables_zip_longest(*iterables, fillvalue=fillvalue):
        # This generator will return the longest iterable's elements
        # or fillvalue if the shorter iterable is exhausted.
        iters = iter(iterables)
        while True:
            try:
                for iterable in iters:
                    yield from iterable
            except StopIteration:
                for iterable in iters:
                    for _ in iterable:
                        yield fillvalue

    # Use zip_longest from itertools to zip the arguments
    return list(iterables_zip_longest(*args, fillvalue=fillvalue))                
              
Tags: