Python Glossary Русский

all Python 3Tuples (tuple)term

zip() with tuples

iteration

zip() works with tuples exactly as it does with lists. It returns an iterator of tuples.

Syntax

zip(t1, t2, ...)

zip stops at the shortest argument without a word, so mismatched tuple lengths silently drop the tail; since Python 3.10 you can pass strict=True to turn that into a ValueError instead. The result is lazy and single-use: once you have consumed it with list() or a for loop, iterating the same zip object again yields nothing.

Examples

t1 = (1, 2, 3)
t2 = ('a', 'b', 'c')
print(list(zip(t1, t2)))  # → [(1, 'a'), (2, 'b'), (3, 'c')]
print(tuple(zip(t1, t2)))  # → ((1, 'a'), (2, 'b'), (3, 'c'))
for x, y in zip((1, 2, 3), ('a', 'b', 'c')):
    print(x, y)  # → 1 a / 2 b / 3 c
keys = ('a', 'b', 'c')
vals = (1, 2, 3)
print(dict(zip(keys, vals)))  # → {'a': 1, 'b': 2, 'c': 3}

See also

Open in the full glossarydocs.python.orgReport an inaccuracy