Zip Longest Iterator for Merging Iterables

  • Share this:

Code introduction


The function is used to merge multiple iterable objects into an iterator. If the length of the iterable objects is not equal, fillvalue is used to fill in the missing values.


Technology Stack : Iterator, Generator

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """Create an iterator that aggregates elements from each of the iterables. 
    The iterator returns pairs of the form (i, tuple), where i is the index of the element from 
    the iterable and tuple is the element from the iterable. 
    If the iterables are of uneven length, missing values are filled-in with fillvalue. 
    Default fillvalue is None."""
    iters = [iter(iterable) for iterable in args]
    while True:
        result = []
        for iter_ in iters:
            try:
                result.append(next(iter_))
            except StopIteration:
                iters.remove(iter_)
        if not result:
            return
        yield result