Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Starred Unpacking: Syntax, Uses, and Pitfalls

Learn how Python's starred unpacking works for assignments, function calls, and function definitions. Includes syntax, edge cases, and performance considerations.

~6 min readPython
#unpacking#function arguments#iterables#kwargs
Illustration of a Python asterisk spreading a list of items into separate boxes, representing starred unpacking.

Python's starred unpacking syntax lets you expand iterables and mappings in assignments and function calls. It appears as a single asterisk (*) for iterables and a double asterisk (**) for mappings. This article explains how Python's starred unpacking works, where it applies, and the mistakes that trip up developers.

The Basic Unpacking Operator

The simplest form of starred unpacking appears in assignment statements. When you write a, b = [1, 2], Python unpacks the list into two variables. The star extends this to capture an arbitrary number of elements:

python
first, *middle, last = [1, 2, 3, 4, 5] print(first) # 1 print(middle) # [2, 3, 4] print(last) # 5

The starred target collects zero or more elements into a list. It can appear at most once per assignment, but it can be placed anywhere among the targets. This works with any iterable, not just lists:

python
head, *tail = (10, 20, 30) print(head) # 10 print(tail) # [20, 30]

A common use is splitting a sequence into its first element and the remainder, which is useful in recursive algorithms or when processing command-line arguments.

Unpacking in Function Calls

Starred unpacking also expands iterables when calling functions. Instead of passing a list as a single argument, you can spread its elements into separate positional parameters:

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

The double star does the same for keyword arguments, but it expects a mapping whose keys match the parameter names:

python
def describe(name, age): return f"{name} is {age} years old" info = {"name": "Ada", "age": 36} print(describe(**info)) # Ada is 36 years old

This pattern is common when delegating to another function or when building calls dynamically. It also works with built-in functions. For example, zip(*pairs) transposes a list of pairs, and print(*items) prints each item as a separate argument.

Extended Unpacking in Assignments

Beyond simple splitting, starred unpacking supports more complex patterns. You can use it to discard unneeded middle fields while keeping the start and end of a record:

python
record = ("John", "Doe", 1985, "NY") name, *_, year, city = record print(name) # John print(year) # 1985

The underscore _ is a conventional placeholder for values you intend to ignore. This is useful when you only need a few fields from a tuple or list.

Starred unpacking also works in for-loop targets. Iterating over a list of tuples and unpacking each one is a standard pattern:

python
points = [(1, 2), (3, 4), (5, 6)] for x, y in points: print(x + y)

You can combine this with a star to capture variable-length segments inside each iteration.

Starred Unpacking in Function Definitions

In function definitions, *args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary. This is the inverse of unpacking in calls:

python
def log(message, *args, **kwargs): print(message) print("args:", args) print("kwargs:", kwargs) log("start", 1, 2, level="info") # start # args: (1, 2) # kwargs: {'level': 'info'}

These parameters are often used for wrappers, decorators, or APIs that need to accept arbitrary arguments. A bare * in a definition forces all following parameters to be keyword-only:

python
def compare(a, b, *, key=None): pass

This improves readability and prevents accidental positional misuse.

Common Mistakes and Edge Cases

One frequent error is using a star with a generator that can be exhausted only once. Unpacking consumes the generator, so you cannot reuse it later. For example:

python
gen = (x for x in range(3)) a, b, c = gen print(list(gen)) # []

Another mistake is attempting to unpack a mapping with a single star. A single star on a dictionary yields its keys, not its values:

python
d = {"x": 1, "y": 2} print(*d) # x y

To unpack values, use *d.values() or **d for keyword arguments.

Starred unpacking requires at least one non-starred target when the iterable is empty. For example, first, *rest = [] raises ValueError: not enough values to unpack. This is a runtime error, not a syntax error, so it can appear in production if input is not validated.

Performance and Memory Considerations

Starred unpacking creates a new list for the starred target. If you unpack a very large iterable, the collected items are materialized in a new container. For a list input such as first, *rest = huge_list, Python creates a second list containing references to all but the first item. That temporarily duplicates the list container's memory, although the contained objects are shared. This is usually acceptable, but for very large data, consider consuming only the parts you need instead of materializing the whole remainder.

Calling a function with *iterable also materializes the expanded arguments in a tuple as part of the call. The overhead is small, but in tight loops it can add up. In such cases, passing a single iterable and iterating inside the function may be more efficient.

**kwargs also has overhead: Python must collect and match keyword arguments, and a **kwargs parameter gathers extra keyword arguments into a dictionary. Building a dictionary just to unpack it adds allocation cost. Prefer explicit keyword arguments when the set is known in advance.

Maintainability and Readability Tradeoffs

Starred unpacking can make code more concise, but it can also obscure intent. Using *args and **kwargs in a public API hides the actual signature, making it harder for callers to know what arguments are expected. This is acceptable for wrappers and decorators, but for core functions, explicit parameters are usually clearer.

Similarly, overusing extended unpacking in assignments can reduce readability. A pattern like a, *b, c = data is fine when the structure is well-known, but if the data format changes, the unpacking will silently produce wrong results or raise errors. Add type hints or comments to document the expected shape.

When you need to ignore many elements, avoid binding a starred target for the ignored portion. A starred assignment target always creates a list, even if you discard it, so use indexes or an iterator that yields only the values you need.

Starred Unpacking with Custom Iterables

Any object that implements __iter__ can be unpacked. This includes custom classes, generators, and file objects. When you unpack a file object line by line, the star will consume the entire file into a list, which is rarely desirable. Prefer iterating directly instead of unpacking.

For mappings, ** works with any object that has keys() and __getitem__, but the standard use is with dictionaries. If you need to merge dictionaries, {**d1, **d2} is a concise idiom that creates a new dictionary. This is often clearer than d1.update(d2) because it does not mutate the original.

Be aware that ** unpacking in dictionary literals is supported from Python 3.5 onward. In earlier versions, you could use dict(d1, **d2) when the keys are strings, or build the merged dictionary with a loop. This version dependency matters if you support legacy environments.

Choosing the Right Unpacking Pattern

The decision between *args, **kwargs, and explicit parameters depends on the stability of the interface. If the function is internal and the argument set is fixed, use explicit names. If you are writing a decorator or a generic dispatch layer, *args and **kwargs are necessary.

For assignment unpacking, use a star when the number of elements varies and you need the remainder. Use fixed targets when the structure is guaranteed. For example, parsing a two-element tuple like (x, y) does not need a star.

When performance matters, measure the actual bottleneck. Starred unpacking is rarely the cause of slow code, but if it appears in a hot loop, consider rewriting the loop to avoid allocation. The standard library's itertools module offers alternatives like islice for partial consumption without copying.

Ultimately, Python's starred unpacking is a versatile feature that, used with discipline, improves code clarity and reduces boilerplate. The key is to match the pattern to the data's actual variability and to document the expected structure so future maintainers can follow the logic.

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.