Python

zip

The zip function takes two collections and merges them. The collections must be of equal length. Collections are : lists, tuples and the dictonaries. All examples are Python 3 code.

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

Zip lists

If we have two lists of eight elements:

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

Just having the data:


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

We can combine them:

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

ab = list(zip(a,b))
print(ab)

The list ab then contains:


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

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:

 
keys=['Hawai','China']
values=['Aloha','Nihao']

ab = dict(zip(keys,values))
print(ab)

This will output:


{‘Hawai’: ‘Aloha’, ‘China’: ‘Nihao’}

 

Previous Post Next Post

Cookie policy | Privacy policy | ©