Combining Iterables with FillValue

  • Share this:

Code introduction


This function combines elements from multiple iterable objects. If the iterable objects are of different lengths, it fills in the missing values with the fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    This function will return an iterator that aggregates elements from each of the iterables. 
    It returns tuples, where the first item is from the first iterable, the second item is from the second iterable, and so on. 
    The iterator stops when the shortest iterable is exhausted, but the longer iterables can still be iterated over. 
    If an iterable is exhausted before the others, missing values are filled-in with the fillvalue.
    """
    # Using zip_longest from itertools, which is a built-in library
    from itertools import zip_longest
    
    return zip_longest(*args, fillvalue=fillvalue)

# JSON output                
              
Tags: