unpacking | Python Glossary – Real Python

In Python, unpacking lets you assign or pass multiple values at once by expanding an iterable into individual items. You’ll see it in assignments for parallel name binding and in expressions and function calls via the iterable unpacking (*) and dictionary unpacking (**) operators.

In assignments, the right-hand side must be an iterable, and the left-hand side is a comma-separated sequence of assignment targets (often written as a tuple of names). The number of values and targets must match. Alternatively, you can use a single starred target (*rest) to collect multiple values into a list.

In function calls, *iterable expands an iterable into positional arguments, while **dictionary expands a dictionary into keyword arguments.

Example

Parallel assignment and value swapping:

>>> a, b = 1, 2
>>> a, b
(1, 2)

>>> a, b = b, a
>>> a, b
(2, 1)

Starred targets:

>>> first, *middle, last = [10, 20, 30, 40]
>>> first
10
>>> middle
[20, 30]
>>> last
40

Function calls:

>>> def greet(greeting, name):
...     return f"{greeting}, {name}!"
...
>>> args = ("Hello", "Pythonista")
>>> greet(*args)
'Hello, Pythonista!'

>>> def connect(host, port, timeout=10):
...     return host, port, timeout
...
>>> conn_params = {"host": "localhost", "port": 8000}
>>> connect(**conn_params)
('localhost', 8000, 10)

Unpacking in expressions:

>>> numbers = [0, *range(1, 4), 4]
>>> numbers
[0, 1, 2, 3, 4]

Here, the result of range(1, 4) is unpacked into the list.

For additional information on related topics, take a look at the following resources: