Combining Iterables with Fillvalue using zip_longest

  • Share this:

Code introduction


This function combines multiple iterable objects into an iterator. If an iterable is exhausted, it continues using a specified fill value.


Technology Stack : Iterator

Code Type : Iterator

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    Return an iterator that aggregates elements from each of the iterables.
    The iterator returns elements from the first iterable until it is exhausted,
    then it returns elements from the second iterable, etc.
    """
    iters = [iter(arg) for arg in args]
    while True:
        yield zip(*iters)                
              
Tags: