Python - Zip (Collection)

1 - About

A zip is a collection constructed from other collections all of the same length.

Zip create pairs of elements when passed two lists, and will stop at the end of the shorter list.

Each element of the zip is a tuple consisting of one element from each of the input collections.

>>> list(zip([1,2],[3,4])) # zip with two list collections
[(1, 3), (2, 4)]
>>> list(zip({1,2},{3,4})) # zip can be used also with set
[(1, 3), (2, 4)]
>>> list(zip({1,2},{3,4,5})) # the 5 will not be an element of the list
[(1, 3), (2, 4)]

3 - Comprehension

Comprehension iteration on zip with unpacking. See Zip

>>> characters = ['Neo', 'Morpheus', 'Trinity']
>>> actors = ['Keanu', 'Laurence', 'Carrie-Anne']
>>> [character+' is played by '+actor for (character,actor) in zip(characters,actors)]
['Neo is played by Keanu', 'Morpheus is played by Laurence', 'Trinity is played by Carrie-Anne']

Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap