Python Glossary Русский

all Python 3Tuples (tuple)term

Tuple unpacking

unpacking

Unpacking assigns the items to variables. * captures the rest. _ is the convention for values that are ignored.

Syntax

a, b = t  |  a, *rest = t  |  a, _, b = t

The usual failure is a count mismatch — ValueError: not enough values to unpack when the names on the left don't match the items on the right. A starred name absorbs the rest, but it always produces a list even when the source was a tuple, and only one star is allowed per assignment. And _ is an ordinary variable: the value really is stored in it, it is just a convention that nobody reads it afterwards.

Examples

a, b, c = (1, 2, 3)
print(a, b, c)
# → 1 2 3
x, y = (10, 20)
x, y = y, x
print(x, y)
# → 20 10 (swap)
first, *rest = (1, 2, 3, 4, 5)
print(first, rest)
# → 1 [2, 3, 4, 5]
*head, last = (1, 2, 3, 4, 5)
print(head, last)
# → [1, 2, 3, 4] 5
a, _, c = (1, 999, 3)
print(a, c)
# → 1 3 (_ игнорируется)
point = (3, 4)
import math
dist = math.sqrt(sum(v**2 for v in point))
print(dist)
# → 5.0
(a, b), c = (1, 2), 3
print(a, b, c)
# → 1 2 3 (вложенная распаковка)
for a, b in [(1, 2), (3, 4)]:
    print(a + b)
    # → 3 / 7

See also

Open in the full glossarydocs.python.orgReport an inaccuracy