Ben Chuanlong Du's Blog

And let it direct your passion with reason.

Unpacking Assignment in Python

The unpacking assignment assigns elements of a tuple/list to variables at once.

In [1]:
x, y, z = (1, 2, 3)
print(x)
print(y)
print(z)
1
2
3

Use _ to capture values to be ignored.

In [3]:
x, y, _ = (1, 2, 3)
print(x)
print(y)
1
2

A variable prefixed with * captures all left values.

In [6]:
x, *y, z = (1, 2, 3, 4)
print(x)
print(y)
print(z)
1
[2, 3]
4

* and _ can be combined togerther to ignore multiple values.

In [2]:
x, *_, z = (1, 2, 3, 4)
print(x)
print(z)
1
4

Comments