Combining Iterables with FillValue

  • Share this:

Code introduction


The function is used to combine multiple iterable objects into an iterator. If one of the iterable objects is shorter, it is padded 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 shortest iterable is padded with fillvalue.
    See: https://docs.python.org/3/library/itertools.html#itertools.zip_longest"
    iterators = [iter(it) for it in iterables]
    while True:
        result = []
        for it in iterators:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        yield result                
              
Tags: