Implementing itertools.zip_longest Functionality

  • Share this:

Code introduction


The function implements the functionality of `itertools.zip_longest`, which is used to merge multiple iterable objects into an iterator. If the length of the iterable objects is uneven, missing values are filled with `fillvalue`.


Technology Stack : itertools

Code Type : Iterator

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "zip_longest(*iterables, fillvalue=fillvalue) -> 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.
    
    Example:
    >>> from itertools import zip_longest
    >>> lst1 = [1, 2, 3]
    >>> lst2 = [4, 5]
    >>> lst3 = [6]
    >>> list(zip_longest(lst1, lst2, lst3))
    [(1, 4, 6), (2, 5, None), (3, None, None)]
    """
    from itertools import zip_longest as zip_longest_implemented

    return zip_longest_implemented(*iterables, fillvalue=fillvalue)                
              
Tags: