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:

Just having the data:

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

We can combine them:

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:

This will output:

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

 

Previous Post
Next Post

Leave a Reply