Merging Iterables with Zip_longest

  • Share this:

Code introduction


This function takes multiple iterable objects as arguments and returns an iterator that merges elements from these iterables. If one of the iterables is shorter than the others, the missing elements are filled with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    Like zip(), but merges elements of shorter iterables until all are exhausted.
    """
    # Using itertools.zip_longest from the itertools module
    from itertools import zip_longest

    return list(zip_longest(*args, fillvalue=fillvalue))                
              
Tags: