Combining Iterables with zip_longest Function

  • Share this:

Code introduction


The `zip_longest` function is used to combine multiple iterable objects into tuples. If the iterable objects are of uneven length, missing values in the shorter iterable objects are filled with `fillvalue`.


Technology Stack : The `zip_longest` function is used to combine multiple iterable objects into tuples. If the iterable objects are of uneven length, missing values in the shorter iterable objects are filled with `fillvalue`.

Code Type : Built-in functions

Code Difficulty : Intermediate


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

    Zip the iterables together into tuples. The zip object is an iterator of tuples
    produced by the zip function. If the iterables are of uneven length, missing values
    in the shorter iterables are filled-in with fillvalue. Default is None.

    Example:
    >>> list(zip_longest('ABCD', 'xy', fillvalue='-'))
    [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')]
    >>> list(zip_longest('ABCD', 'xy', fillvalue='z'))
    [('A', 'x'), ('B', 'y'), ('C', 'z'), ('D', 'z')]"
    """
    from itertools import zip_longest
    return zip_longest(*iterables, fillvalue=fillvalue)