Zip Longest Function in Python

  • Share this:

Code introduction


This function uses the zip_longest function from the itertools library to merge multiple iterable objects. If the objects are of unequal length, it fills in the missing parts with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Return an iterator that aggregates elements from each of the iterables. 
    The iterator returns pairs of the form (i, val), where i is the index of the element 
    from the iterable and val is the element obtained from the iterable. 
    The iterator stops when the shortest iterable is exhausted, 
    filling in missing values with fillvalue.
    """
    # Using zip_longest from itertools, which is an extension of zip that allows 
    # filling in missing values with fillvalue when the iterables are of unequal length
    from itertools import zip_longest

    return zip_longest(*args, fillvalue=fillvalue)

# JSON representation of the code                
              
Tags: