Combining Iterables with Zip Longest

  • Share this:

Code introduction


This function uses the zip_longest function from the itertools library to combine multiple iterable objects into a list of tuples. If one of the iterable objects has been fully traversed, it is filled with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


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

    def generate_tuples():
        iters = [iter(args[i]) for i in range(len(args))]
        for tup in zip_longest(*iters, fillvalue=fillvalue):
            yield tup

    result = list(generate_tuples())
    return result                
              
Tags: