The zip function takes two collections and merges them. The collections must be of equal length.

So what is a collection? Collections are : lists, tuples and the dictonaries. All examples are Python 3 code.

Related Course:

Zip lists

The example below creates two lists, list a and list b. Each list consists of 8 elements.

Instead of manually defining each value, the range function is used to fill the contents of the list. This is not mandatory, it’s only for this example.

a = list(range(8))
b = list(range(8))

These lists have the data:

[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7]

We can combine them with the zip function into a combined list.

a = range(8)
b = range(8)

ab = list(zip(a,b))

The list ab then contains:

python zip

All elements in the list are now pairs. If we merge three lists, we would get a pair of 3 for each element.

Note: When you zip() together two lists containing 8 elements each, the result has eight elements.

Zip dictionary

We can convert two lists to a dictionary:


ab = dict(zip(keys,values))

This will output:

{'Hawai': 'Aloha', 'China': 'Nihao'}

Download exercises