Python Function: zip_longest with itertools.zip_longest

  • Share this:

Code introduction


This function uses `itertools.zip_longest` to create an iterator that aggregates elements from each of the provided iterables. If the iterables are of unequal length, missing values are filled in with `fillvalue`. The default fill value is `None`.


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.
    
    Returns a list using `zip` that aggregates elements from each of the iterables.
    If the iterables are of uneven length, missing values are filled-in with `fillvalue`.
    Defaults to filling in `None`.
    
    Example:
    >>> list(zip_longest([1, 2, 3], [4, 5], [6], fillvalue=0))
    [(1, 4, 6), (2, 5, None), (3, None, None)]
    """
    # Use itertools.zip_longest to achieve the same functionality as zip_longest
    from itertools import zip_longest
    return list(zip_longest(*iterables, fillvalue=fillvalue))                
              
Tags: