Python Glossary Русский

all Python 3Loopsfunction

zip()

iteration

Built-in function that joins several iterables into one. It returns tuples of the corresponding items. It stops at the shortest one.

Syntax

zip(*iterables)

In Python 3 zip() returns a lazy iterator, not a list, and is used up after one pass — wrap it in list() if you need to iterate twice or index into it. The zip(*pairs) idiom unzips a list of pairs back into separate sequences, and applied to a matrix's rows it transposes it.

Examples

names = ["Анна", "Борис", "Вера"]
scores = [95, 78, 88]
for name, score in zip(names, scores):
    print(f"{name}: {score}")  # → Анна: 95 / Борис: 78 / Вера: 88
a, b, c = [1, 2], [3, 4], [5, 6]
for x, y, z in zip(a, b, c):
    print(x + y + z, end=" ")  # → 9 12
print(dict(zip(['a', 'b', 'c'], [1, 2, 3])))  # → {'a': 1, 'b': 2, 'c': 3}
print(list(zip([1, 2, 3], [4, 5])))  # → [(1, 4), (2, 5)] — по короткому
from itertools import zip_longest
print(list(zip_longest([1, 2, 3], [10, 20], fillvalue=0)))  # → [(1, 10), (2, 20), (3, 0)]

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy