Generating Tuples from Iterables with FillValue

  • Share this:

Code introduction


The function takes multiple iterable objects as arguments and returns an iterator that generates tuples, each containing elements taken from each iterable. If an iterable is exhausted, fillvalue is used to fill in the missing elements.


Technology Stack : The function takes multiple iterable objects as arguments and returns an iterator that generates tuples, each containing elements taken from each iterable. If an iterable is exhausted, fillvalue is used to fill in the missing elements.

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    iters = [iter(arg) for arg in args]
    while True:
        result = []
        for i, it in enumerate(iters):
            try:
                result.append(next(it))
            except StopIteration:
                iters[i] = iter([fillvalue])
                result.append(fillvalue)
        if all(fillvalue in result for fillvalue in args):
            break
        yield tuple(result)