Python zip Function: Aggregating Elements and Handling Uneven Lengths

  • Share this:

Code introduction


The zip function combines elements from each of the iterables into tuples, returning an iterator. If the iterables are of uneven length, missing values in the shorter iterables will be filled in with fillvalue, which defaults to None.


Technology Stack : Built-in function

Code Type : Built-in functions

Code Difficulty : Intermediate


                
                    
def zip(*iterables):
    "zip(*iterables) -> zip object"
    """Make an iterator that aggregates elements from each of the iterables.

    For example, zipped('abc', '123') -> 'a', '1', 'b', '2', 'c', '3'.

    If the iterables are of uneven length, missing values in the shorter
    iterables will be filled-in with fillvalue. fillvalue defaults to None.

    """
    # zip is a built-in function in Python 3. In Python 2, zip is in the itertools module.
    import itertools
    return itertools.zip_longest(*iterables, fillvalue=None)