Extended Zip Function for Uneven Length Iterables

  • Share this:

Code introduction


The function is similar to the built-in zip function but can handle iterables of uneven length. If the iterables are of different lengths, it fills in the missing values with the fillvalue.


Technology Stack : zip, iter, next, StopIteration

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """
    Like zip() but the output list is extended with fillvalues if the iterables are of uneven length.
    """
    iterators = [iter(arg) for arg in args]
    while True:
        result = []
        for it in iterators:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        if len(result) == len(args):
            return result
        else:
            iterators = [iter(arg) for arg in args]