Handling Unequal Length Iterables with zip_longest

  • Share this:

Code introduction


This function implements a similar function to zip, but can handle data sequences of unequal length. When the sequence length is unequal, missing values are filled with fillvalue.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "zip(*iterables) -> zip object\n\n    Make an iterator that aggregates elements from each of the iterables.\n\n    Returns an iterator that produces tuples containing elements from the iterables.\n\n    The iterator stops when the shortest iterable is exhausted, and fills in missing values with fillvalue.\n\n    Examples\n    =========\n\n    >>> list(zip_longest('ABCD', 'xy', fillvalue='-'))\n    [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')]  # doctest: +NORMALIZE_WHITESPACE\n\n    >>> list(zip_longest('ABCD', 'xyzz', fillvalue='-'))\n    [('A', 'x'), ('B', 'y'), ('C', 'z'), ('D', '-')]  # doctest: +NORMALIZE_WHITESPACE\n\n    >>> list(zip_longest([1, 2, 3], [4, 5], [6], fillvalue=0))\n    [(1, 4, 6), (2, 5, None), (3, None, None)]\n\n    Args:\n        *iterables: An arbitrary number of iterables.\n        fillvalue: The value to use for missing values if the iterables are of uneven length.\n\n    Returns:\n        An iterator\n    "
    iterators = [iter(it) for it in iterables]
    for i in iterables:
        for it in iterators:
            try:
                yield next(it)
            except StopIteration:
                yield fillvalue