Python zip() function takes iterables (can be zero or more), makes an iterator that aggregates elements based on iterators you give, then returns an iterator of tuples. In this tutorial, we will discuss how to this function with some examples.
Syntax : zip(*iterators) Parameters : Python iterables or containers ( list, string etc ) Return Value : Returns a single iterator object, having mapped values from all the containers.
Example 1: zip three lists with same length
x = [1, 2, 3] y = [4, 5, 6] z = [7, 8, 9] xyz = zip(x, y, z) print xyz
The output is:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
The output is a list of tuples.
Example 2: zip two list with different length
x = [1, 2, 3] y = [4, 5, 6, 7] xy = zip(x, y) print xy
The output is:
[(1, 4), (2, 5), (3, 6)]
From output, we find Extra element in y is abandoned.
Example 3: zip only a list
x = [1, 2, 3] x = zip(x) print x
The output is:
[(1,), (2,), (3,)]
Example 4: zip empty list
x = zip() print x
The output is:
[]