Advanced Zip Functionality with FillValue

  • Share this:

Code introduction


The `zip_longest` function is similar to the built-in `zip` function, but it returns an iterator where the length of the element lists matches the longest input iterable. Shorter iterables are padded with the `fillvalue`.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "zip_longest(*iterables, fillvalue=None) -> zip_longest object\n\n    Like zip(), but the output list lengths match the longest iterable.\n    Shorter iterables are padded with fillvalue.\n\n    >>> list(zip_longest([1, 2, 3], [4, 5], fillvalue=0))\n    [(1, 4), (2, 5), (3, 0)]\n    >>> list(zip_longest([1, 2, 3, 4], [5, 6], fillvalue=0))\n    [(1, 5), (2, 6), (3, 0), (4, 0)]\n    "
    from itertools import zip_longest as _zip_longest
    return _zip_longest(*iterables, fillvalue=fillvalue)                
              
Tags: