Enhanced Zip Function for Uneven Iterable Lengths

  • Share this:

Code introduction


This function zips together multiple iterable objects and fills in missing values with a specified fill value if the lengths of the iterables are uneven.


Technology Stack : Built-in libraries

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """Zips together multiple iterables but fills in missing values if the iterables are of uneven length.

    Args:
        *args: An arbitrary number of iterables to zip.
        fillvalue: The value to use for missing values in the shorter iterables.

    Returns:
        An iterator that aggregates elements from each of the iterables.

    Example:
        >>> list(zip_longest([1, 2, 3], [4, 5], fillvalue=0))
        [(1, 4), (2, 5), (3, 0)]
    """
    iters = [iter(iterable) for iterable in args]
    longest_iterable_length = max(len(iterable) for iterable in iters)
    for i in range(longest_iterable_length):
        for j, iterable in enumerate(iters):
            try:
                yield next(iterable)
            except StopIteration:
                iters[j] = iter([fillvalue])