Python zip() Function


The zip() function accepts a series of iteratable objects as arguments, packages the corresponding elements of different objects into a tuple, and returns a list consisting of these tuples.

If the length of the incoming argument is not equal, then the list returned is the same length as the shortest object in the incoming argument.

Related course: Complete Python Programming Course & Exercises

Syntax

zip([iterable, ...])

Basic understanding of Python zip() function

If you have two lists, you can zip() them like zip(x,y):

x = [1,2,3,4,5]
y = ['a','b','c','d']
xy = zip(x,y)
print xy
for a,b in zip(x,y):
    print(a)
    print(b)

Results in:

[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
1
a
2
b
3
c
4
d

python zip function

Example 2 So what if you only have one argument in zip() ? The program below shows.

x = [1,2,3,4,5]
xx = zip(x)
print(xx)
for a in zip(x):
    print(a)
for a in zip(x):
    print(a[0])

Outputs:

[(1,), (2,), (3,), (4,), (5,)]
(1,)
(2,)
(3,)
(4,)
(5,)
1
2
3
4
5

Example 3 Here's another example of the zip function, this time with a dynamic size parameters.

x = [[1,2,3,4],['a','b','c'],[7,8,9]]
y = zip(*x)
print(y)
for a in y:
    print(a)
for a,b,c in zip(*x):
    print(a)
    print(b)
    print(c)

This outputs:

[(1, 'a', 7), (2, 'b', 8), (3, 'c', 9)]
(1, 'a', 7)
(2, 'b', 8)
(3, 'c', 9)
1
a
7
2
b
8
3
c
9

Another zip() example Just for understanding, here is another example of the zip function.

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # Packaged list of tuple
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # The number of elements matches the shortest list
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # In contrast to zip, which can be understood as decompression, the inverse process of zip can be used to transpose the matrix
[(1, 2, 3), (4, 5, 6)]