Merging Iterables with FillValue

  • Share this:

Code introduction


The function is used to merge multiple iterable objects. If their lengths are different, a specified fill value is used to fill in the missing parts.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "Make an iterator that aggregates elements from each of the iterables.
    The iterables must have the same length or be empty.
    If the iterables are of uneven length, missing values are filled-in with fillvalue.
    Parameters
    ----------
    iterables : sequence
        An iterable of iterables (each producing a stream of values like an iterator).
    fillvalue : optional
        The value to use for missing values if the iterables are of uneven length.
    Returns
    -------
    iterator
        An iterator that aggregates elements from the iterables.
    Examples
    --------
    >>> list(zip_longest([1, 2, 3], [4, 5], fillvalue=0))
    [1, 4, 2, 5, 3, 0]
    >>> list(zip_longest([1, 2, 3, 4], [5, 6], fillvalue=7))
    [1, 5, 2, 6, 3, 7, 4, 7]
    """
    from itertools import zip_longest
    return zip_longest(*iterables, fillvalue=fillvalue)                
              
Tags: