Creating an Aggregated Iterator with FillValue

  • Share this:

Code introduction


The function creates an iterator that aggregates elements from each of the iterables. It 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 that iterable. If the iterables are of different lengths, a fillvalue is used for missing values.


Technology Stack : Iterator, generator expression

Code Type : Iterator

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "Make 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 that iterable.
    The iterables must all be of the same length or the fillvalue is used for
    missing values.  The iterator stops when the shortest iterable is exhausted."
    iterators = [iter(it) for it in iterables]
    while True:
        result = []
        for it in iterators:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        if fillvalue is not None:
            if all(v is fillvalue for v in result):
                break
        else:
            if not all(v is not None for v in result):
                break
        yield tuple(result)