Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Extended Unpacking: Syntax and Practical Uses

Understand Python's extended unpacking syntax for assignments, function calls, and iterable handling, with practical examples and common pitfalls.

~5 min readPython
#unpacking#star-expressions#args#kwargs
Illustration of Python extended unpacking showing values being distributed from a list into multiple variables and function arguments.

Python's extended unpacking syntax lets you assign multiple values from an iterable in one statement, and it also changes how you can pass arguments to functions. Starred expressions appear in assignments, for-loop targets, and function calls, and they often replace manual indexing or slicing.

What Extended Unpacking Does

Basic unpacking has been part of Python for a long time: a, b = 1, 2 assigns 1 to a and 2 to b. Extended unpacking adds a starred expression, written with a single asterisk, that captures a variable-length portion of the iterable. For example:

python
first, *rest = [1, 2, 3, 4] print(first) # 1 print(rest) # [2, 3, 4]

The starred target *rest collects all remaining elements into a list. This works with any iterable, not just lists. The starred expression can appear in any position, so you can capture the middle or the tail:

python
head, *middle, tail = range(5) print(head) # 0 print(middle) # [1, 2, 3] print(tail) # 4

Unpacking Sequences and Iterables

Because unpacking works on any iterable, you can use it with tuples, strings, generators, and custom iterable objects. A string unpacks into individual characters:

python
first, *middle, last = 'python' print(first, middle, last) # p ['y', 't', 'h', 'o'] n

Generators can be unpacked too. A starred target consumes the generator item by item and stores all remaining values in a list. For a very large generator, that can use significant memory; for an infinite generator, it never finishes.

You can also unpack nested structures. For instance, a list of pairs can be unpacked in a for loop:

python
pairs = [(1, 'a'), (2, 'b')] for number, letter in pairs: print(number, letter)

With extended unpacking, you can capture a variable number of trailing elements from each row:

python
data = [(1, 'a', 'x'), (2, 'b', 'y', 'z')] for number, *letters in data: print(number, letters) # 1 ['a', 'x'] # 2 ['b', 'y', 'z']

Using *args in Function Calls

In a function call, a starred expression expands an iterable into positional arguments. This is commonly used when you have a list or tuple of values that must be passed individually:

python
def add(a, b, c): return a + b + c values = [1, 2, 3] print(add(*values)) # 6

This is equivalent to add(1, 2, 3). A starred expression can be mixed with other positional arguments. In Python 3.5 and later, multiple starred expressions are allowed in one call:

python
first = [1, 2] second = [3, 4] print(*first, *second) # 1 2 3 4

Before Python 3.5, a function call could contain only one starred expression.

In a function definition, *args collects extra positional arguments into a tuple. The name args is a convention, not a requirement. This is the inverse operation: it gathers arguments rather than expanding them.

Using **kwargs for Keyword Arguments

The double-star syntax ** works with keyword arguments. In a function call, **mapping expands a dictionary into keyword arguments:

python
def greet(name, greeting='Hello'): print('{}, {}'.format(greeting, name)) kwargs = {'name': 'Ada', 'greeting': 'Hi'} greet(**kwargs) # Hi, Ada

The dictionary keys must be strings, and any key that does not match a parameter name is rejected unless the function accepts **kwargs.

In a function definition, **kwargs collects any unexpected keyword arguments into a dictionary. This pattern is common in wrappers and decorators where you need to forward arbitrary options.

Extended Unpacking in Assignments

PEP 3132 introduced starred assignment targets in Python 3.0. This allows you to unpack an iterable into a fixed number of variables and capture the rest in a list. The starred target must appear exactly once in the assignment target list. You cannot use two starred expressions in the same assignment:

python
# Invalid: two starred targets *a, *b = [1, 2, 3]

You also cannot use a starred expression as the only target. For example, *a = [1, 2] is a syntax error because there is no fixed target to anchor the unpacking.

When the iterable has exactly the same number of elements as the fixed targets, the starred target receives an empty list:

python
a, *b = [1] print(a, b) # 1 []

If the iterable has fewer elements than the fixed targets, Python raises a ValueError:

python
a, *b = [] # ValueError: not enough values to unpack

Common Pitfalls and Edge Cases

One frequent mistake is assuming that a starred target always produces a list in an assignment. It does, even if the original iterable is a tuple or a string. This is a deliberate design choice to make the result predictable.

When unpacking in a for loop, the loop variable receives the same treatment. If you have a list of lists with varying lengths, you can use *rest to capture the tail, but the loop will still iterate over every element, so this is not a filtering mechanism.

Function call unpacking can be confusing when combined with keyword arguments. For example, you cannot use * to expand a dictionary; that requires **. Mixing them is allowed, but keep normal argument order: positional arguments come first, then keyword arguments.

Performance and Maintainability Considerations

Extended unpacking is a core interpreter operation and is generally efficient. The main cost when unpacking in an assignment is the allocation of a list for the starred target. For a large iterable, this can be a memory concern. If you only need the first few elements and want to avoid materializing the rest, consider using itertools.islice instead.

In function calls, a starred expression supplies positional arguments as a tuple, and **mapping supplies keyword arguments as a dictionary. These allocations are usually negligible, but they become relevant in tight loops or when passing very large collections.

From a maintainability perspective, extended unpacking often improves readability by expressing intent directly. Compare first, rest = values[0], values[1:] with first, *rest = values. The latter works with any iterable and avoids indexing and slicing. However, overusing nested unpacking can make code harder to follow. Use it when the structure of the data matches the pattern you are extracting.

Compatibility with Python Versions

Extended unpacking in assignments (starred targets) has been available since Python 3.0. The generalization that allows multiple starred expressions in function calls and in list, tuple, and set displays was added in Python 3.5 (PEP 448).

Python 2 does not support starred assignment targets or the PEP 448 generalizations. It does support a single *args and **kwargs in function calls, but not the assignment-target form of extended unpacking. For assignments in Python 2, use slicing or explicit indexing.

For modern projects that require Python 3.5 or later, you can safely use the full extended unpacking syntax. The core syntax has been stable since 3.5, so code using these forms does not need changes when moving between modern Python 3 releases.

One version-specific detail: in Python 3.5 and later, you can use starred expressions in list, tuple, and set displays, such as [*a, *b]; ** is also allowed in dictionary displays, as in {**d1, **d2}. This is a natural extension of the same idea, but it is not part of the original assignment unpacking feature. Understanding the version history helps you decide which constructs are safe in a given codebase.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.