PythonBuilt-in functions
zip()
Pairs up (or groups into tuples) the matching items of several collections.
- Returns
- An iterator of tuples.
Example
#Python
names = ["Emma", "Jack", "Mia"]
scores = [92, 78, 85]
for name, score in zip(names, scores):
print(f"{name}: {score}")
print(dict(zip(names, scores)))Resultsaved result, you can check it
Emma: 92
Jack: 78
Mia: 85
{'Emma': 92, 'Jack': 78, 'Mia': 85}
Definition and usage
#The zip() function walks through several collections at the same time and returns tuples of items from the same position: the first tuple holds the first items, the second tuple the second items, and so on.
By default it stops at the shortest collection, and the extra items of longer ones are dropped. Since Python 3.10, the strict=True parameter raises an error when the lengths differ.
Typical uses are looping over two lists at once, building a dictionary with dict(zip(keys, values)), and 'transposing' a list of pairs with zip(*pairs).
Syntax
#Syntax
zip(*iterables, strict=False)Parameters
#*iterables
collections
The collections to combine.strict
bool, default False
WhenTrue, different lengths raise aValueError.
More examples
#Python
print(list(zip([1, 2, 3], ["a", "b"])))
pairs = [("html", 11), ("css", 9)]
courses, modules = zip(*pairs)
print(courses, modules)Resultsaved result, you can check it
[(1, 'a'), (2, 'b')]
('html', 'css') (11, 9)
Good practices
#- When lists should have the same length, use
zip(..., strict=True)to catch mistakes in the data. - To walk through lists of different lengths completely, use
itertools.zip_longest().
Related entries
#Spotted a mistake or missing an example? Write to us.