Imitation of itertools.zip_longest without Using itertools

  • Share this:

Code introduction


This function mimics the behavior of the `itertools.zip_longest` without using the `itertools` package. It combines multiple iterable objects into an iterator, filling with `fillvalue` if some iterables are of different lengths.


Technology Stack : Built-in Python libraries

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """
    This function mimics the `itertools.zip_longest` behavior without using the `itertools` package.
    """
    iters = [iter(arg) for arg in args]
    while True:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        yield tuple(result)