Combining Iterables with Fillvalue in Python

  • Share this:

Code introduction


The function is used to combine multiple iterable objects into an iterator. If the iterable objects are of uneven length, missing values are filled with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "Make an iterator that aggregates elements from each of the iterables.
    The iterables must have the same length or be empty. If the iterables are of
    uneven length, missing values are filled-in with fillvalue. Default is None."
    zipped = zip(*iterables)
    return iter(lambda: tuple(itertools.chain(*zipped)), ())                
              
Tags: