Python’s zip() function can combine series/iteratable objects as arguments and returns a list of packaged tuples.
If the length of the iterables isn’t equal, then the list returned is that the same length because the shortest sequence.
Syntax
zip([iterable, ...])
Related course: Complete Python Programming Course & Exercises
Python zip() function
The zip() function can combine two lists like this 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)
The program above results in:
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
1
a
2
b
3
c
4
d
Demo 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
Demo 3
Here’s another demo 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() demo
Just for understanding, here is another demo 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)]
Related course: Complete Python Programming Course & Exercises