Combining Iterables with FillValue in Python

  • Share this:

Code introduction


The function is used to combine multiple iterable objects into an iterator. If one iterable object ends early, the other iterable objects continue to output using the specified fill value.


Technology Stack : Python built-in library

Code Type : Built-in library functions

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "Make an iterator that aggregates elements from each of the iterables."
    "The iterator returns elements from the first iterable until it is exhausted, then"
    "moves to the next iterable, until all of the iterables are exhausted."
    "fillvalue is used for missing values when the iterables are of uneven length."
    "Example: zip_longest('abc', 'x', 'wxyz', fillvalue='-') -> ('a', 'x', 'w'), ('b', 'x', 'x'), ('c', 'x', 'y'), ('-', 'x', 'z')"
    iterators = [iter(it) for it in iterables]
    while True:
        result = []
        for it in iterators:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        if len(result) < len(iterables):
            break
        yield result