Python zip() function

Updated on Jan 07, 2020


The zip() function takes one or more sequences and combines the corresponding items in the sequences into a tuple. It stops when the shortest sequence is exhausted. In Python 2, zip()  returns an actual list which is not very efficient if you work with a large amount of data. For this reason, in Python 3, zip() returns an iterable which produces the result on demand.

Syntax: zip(iter1 [,iter2 [...]]) --> zip object

Python 3

1
2
3
4
>>>
>>> zip([1, 2, 3, 4], "pow")
<zip object at 0x7f3c1ceb51c8>
>>>

To produce the result wrap the zip() in a list() call.

1
2
3
4
>>>
>>> list(zip([1, 2, 3, 4], "pow"))
[(1, 'p'), (2, 'o'), (3, 'w')]
>>>

Try it out:

zip_obj = zip([1, 2, 3, 4], "pow")
print(list(zip_obj))


Python 2

1
2
3
4
>>>
>>> zip([1, 2, 3, 4], "pow") # In Python 2, list() call is not required
[(1, 'p'), (2, 'o'), (3, 'w')]
>>>

Here is one practical example, where zip() is used to iterate multiple sequences in parallel.

1
2
3
4
5
6
7
8
>>>
>>> for i, j, k, l in zip([1, 2, 3], "foo", ("one", "two", "three"), {"alpha", "beta", "gamma"}):
...   print(i, j, k, l)
...
1 f one alpha
2 o two gamma
3 o three beta
>>>

Try it out:

for i, j, k, l in zip([1, 2, 3],  "foo", 
                      ("one", "two", "three"), 
                      {"alpha", "beta", "gamma"}
                     ):
    print(i, j, k, l)


Here is another example where zip() function is used to create a dictionary.

1
2
3
4
5
6
7
8
>>> 
>>> keys = ['alpha', 'beta', 'gamma']
>>> values = [10, 20, 30]
>>> 
>>> d = dict(zip(keys, values))
>>> d
{'alpha': 10, 'beta': 20, 'gamma': 30}
>>>

Try it out:

keys = ['alpha', 'beta', 'gamma']
values = [10, 20, 30]
 
d = dict(zip(keys, values))
print(d)



Other Tutorials (Sponsors)