Creating an Extended Zip Function

  • Share this:

Code introduction


This function creates an iterator that aggregates elements from each of the iterables. The shortest iterable is repeated until the longest is exhausted. If an iterable is exhausted, it can be filled with a value specified by fillvalue.


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 shortest iterable is repeated until the longest is exhausted.
    Parameters
    ----------
    *iterables : iterables
        An iterable of iterables
    fillvalue : value, optional
        Value to use for missing values from iterables that are exhausted
    Examples
    --------
    >>> list(zip_longest([1, 2, 3], [4, 5], [6], fillvalue=0))
    [(1, 4, 6), (2, 5, None), (3, None, None)]
    >>> list(zip_longest('abc', 'de', fillvalue='*'))
    [('a', 'd', '*'), ('b', 'e', '*'), ('c', None, '*')]
    """
    from itertools import zip_longest
    return zip_longest(*iterables, fillvalue=fillvalue)                
              
Tags: