Combining Iterables with Fill Value Support

  • Share this:

Code introduction


The function combines elements from multiple iterable objects into an iterator. If the length of the iterables is uneven, missing values are filled with a specified fill value.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "zip_longest(*iterables, fillvalue=None) -> zip_longest object
    Make an iterator that aggregates elements from each of the iterables.
    The iterator returns pairs from the iterables. If the iterables are of uneven
    length, missing values are filled-in with fillvalue. fillvalue defaults to
    None.
    
    Examples:
    >>> list(zip_longest('ABCD', 'xy', fillvalue='-'))
    ['A', 'x', '-']
    >>> list(zip_longest('ABCD', 'xy', fillvalue='*'))
    ['A', 'x', '*', 'D']
    >>> list(zip_longest('ABCD', 'xy'))
    ['A', 'x', 'B', 'y', 'C', 'D']
    """
    from itertools import zip_longest as zip_longest_from_itertools
    return zip_longest_from_itertools(*iterables, fillvalue=fillvalue)                
              
Tags: