Combining Iterables with Fillvalue Using zip_longest

  • Share this:

Code introduction


The function utilizes the zip_longest function from the itertools module, which combines elements from each of the provided iterable objects into a single iterator. If the iterables are of different lengths, missing values are filled in with the fillvalue parameter.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "zip_longest(*iterables, fillvalue=None) -> zip object

    Make an iterator that aggregates elements from each of the iterables.

    If the iterables are of uneven length, missing values are filled-in with
    fillvalue. Default is None.

    Examples:
    >>> list(zip_longest([1, 2, 3], [4, 5], [6, 7, 8]))
    [(1, 4, 6), (2, 5, 7), (3, 8, None)]
    >>> list(zip_longest([1, 2, 3], [4, 5], fillvalue='x'))
    [(1, 4, 'x'), (2, 5, 'x'), (3, None, 'x')]
    """
    from itertools import zip_longest as itzip_longest
    return itzip_longest(*iterables, fillvalue=fillvalue)                
              
Tags: