Combining Iterables with Fillvalue

  • Share this:

Code introduction


This function combines multiple iterable objects into tuples of equal length, filling in missing values with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """Combine several iterables into tuples of equal length, filling missing values with fillvalue."""
    iterators = [iter(arg) for arg in args]
    while True:
        result = [next(it, fillvalue) for it in iterators]
        if fillvalue in result:
            return
        yield tuple(result)                
              
Tags: