Python zip() Function

The zip() function in Python is used when we need to combine two iterators. For example:

a = [1, 2, 3]
b = [4, 5, 6]

x = zip(a, b)
print(tuple(x))

The output is:

((1, 4), (2, 5), (3, 6))

That is, zip() returns a zip object. The returned object is basically an iterator where first item in each passed iterators is paired together, similar things goes with second, third, fourth, and all items.

Note: If iterators are of different length, then the length of iterator returned by zip() will be equal to the length of iterator with least number of items.

Python zip() Function Syntax

The syntax of zip() function in Python, is:

zip(iterator1, iterator2, iterator3, ..., iteratorN)

Python zip() Function Example

Here is an example of zip() function in Python:

a = [1, 2, 3]
b = [4, 5, 6]
x = zip(a, b)
print(tuple(x))

a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]
x = zip(a, b)
print(tuple(x))

a = [1, 2, 3, 4, 5, 6]
b = [7, 8, 9, 10, 11]
x = zip(a, b)
print(tuple(x))

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
c = (9, 10, 11, 12)
d = {13, 14, 15, 16}
x = zip(a, b, c, d)
print(list(x))

a = {"Day": "Mon", "Month": "Dec"}
b = [1, 2, 3]
x = zip(a, b)
print(set(x))

The output is:

((1, 4), (2, 5), (3, 6))
((1, 5), (2, 6), (3, 7), (4, 8))
((1, 7), (2, 8), (3, 9), (4, 10), (5, 11))
[(1, 5, 9, 16), (2, 6, 10, 13), (3, 7, 11, 14), (4, 8, 12, 15)]
{('Day', 1), ('Month', 2)}

If dictionary is used as iterator, then the key will get considered as element to aggregate with other iterator.

Python Online Test


« Previous Function Next Function »