Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Nested Unpacking: Syntax and Patterns

Learn how to unpack nested tuples and lists in Python, use star expressions for variable-length data, and avoid common dictionary and string pitfalls.

~5 min readPython
#unpacking#tuple unpacking#destructuring#python syntax
Diagram showing a nested tuple structure being unpacked into separate variables in Python

Python's nested unpacking lets you assign multiple names from a nested iterable in a single statement. This syntax is sometimes called destructuring. For example, when you receive a tuple like (1, (2, 3)), you can bind all three values at once:

python
point = (1, (2, 3)) x, (y, z) = point print(x, y, z) # 1 2 3

The left side of the assignment mirrors the shape of the right side. Nested unpacking is not limited to tuples; lists, strings, and custom iterables follow the same rules.

How Nested Unpacking Works

During an unpacking assignment, Python matches items from the right-side iterable with targets on the left in order. When a target is itself a nested pattern, such as (y, z), Python expects the corresponding value to be an iterable with exactly that many elements.

python
nested = [1, [2, 3], 4] a, (b, c), d = nested print(a, b, c, d) # 1 2 3 4

If a nested value is not iterable or its length does not match, Python raises an error such as TypeError: 'int' object is not iterable or ValueError: too many values to unpack (expected 2). The failure happens during the assignment, so unpacking can also validate that data has the shape you expect.

You can use nested patterns beyond one level, but the left side must mirror the right side. Deeply nested patterns are rare in practice because they reduce readability; keep patterns shallow.

Unpacking with Star Expressions

When part of the structure has variable length, use a star expression (*name) to capture multiple elements into a list. This works at any level of nesting.

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

Inside a nested pattern, the star expression applies to that level only. For example:

python
a, (b, *c), d = [1, [2, 3, 4], 5] print(a, b, c, d) # 1 2 [3, 4] 5

Here c captures all elements after the first in the inner list. Within one level of a pattern, the star expression can appear once, and it must be followed by a name. It can appear at the beginning, middle, or end of that level.

Star expressions are useful when parsing records with a fixed prefix or suffix but a variable middle section:

python
record = ["2024-01-01", "web", "auth", "login"] timestamp, *tags, message = record

This binds tags to ["web", "auth"] and message to "login". If the record has no middle tokens, tags is an empty list, which is often the desired behavior.

Nested Unpacking in Loops

A common use case is iterating over a sequence of records where each record has a nested structure. Unpacking in a for loop avoids indexing and makes the intent explicit.

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

This is clearer than writing for p in points: x = p[0]; y = p[1][0]; z = p[1][1]. The unpacking version also fails early if a record has the wrong shape, which can help catch data quality issues during development.

You can combine star expressions with loop unpacking to handle records of varying length. For example, a list of exam results where each entry starts with a student ID and is followed by an arbitrary number of scores:

python
results = [("A1", 90, 85), ("B2", 88), ("C3", 75, 92, 81)] for student_id, *scores in results: print(student_id, sum(scores) / len(scores))

If a record can contain no scores, guard against len(scores) == 0 before dividing.

Common Mistakes and Edge Cases

Nested unpacking fails when the structure does not match exactly. Watch out for strings: unpacking a string yields characters, not substrings.

python
a, b = "xy" # a='x', b='y'

If you use a nested pattern with a string, the pattern must match the string's character length.

Another edge case is dictionaries. Iterating over a dictionary yields its keys, not key-value pairs. To unpack both keys and values, use .items():

python
for key, value in data.items(): print(key, value)

When you unpack a custom object, Python uses its iterator protocol. If the object is not iterable, Python raises a TypeError.

Trailing commas are also a common point of confusion. a, = value unpacks a one-element iterable. a, (b, c), = value is a valid two-target list with a trailing comma, not a syntax error. The comma is required for a one-element tuple pattern, but in a nested target pattern it is rarely needed and can make the code harder to read.

Performance and Memory Considerations

Unpacking itself binds names to existing objects; it does not copy the underlying data. Star expressions do create a new list for the captured elements. If the iterable is large and you only need a few elements, a star expression can allocate more than you need:

python
first, *rest = large_list

This copies all remaining references into a new list. If you only need the first element, first = large_list[0] is more memory-efficient. The list creation is O(n) in the number of captured elements.

Star expressions also affect generators. An unpacking assignment consumes the generator as it requests items. For an exact-count pattern such as a, b = gen, Python asks for two items and does not exhaust the generator. With a star expression, Python pulls items from the generator until it is exhausted to fill the starred list, which materializes all remaining items. If that list could be large, consider a loop or itertools.islice instead.

When to Use Nested Unpacking vs Alternatives

Nested unpacking is best when the data structure is fixed and known at write time. It makes the shape of the data visible in the code and eliminates index-based access. For more complex or frequently changing data, consider namedtuple, dataclass, or a dictionary. These approaches provide named access and are more maintainable when the number of fields grows. Unpacking a namedtuple works exactly like unpacking a tuple, so you can still use the syntax when you need to extract values quickly.

ApproachBest forUnpacking support
Nested unpackingFixed, short structuresNative
IndexingDynamic access, but verboseNo
namedtupleNamed fields plus tuple behaviorYes
dataclassMutable, complex objects with methodsNo (unless custom)
DictionaryDynamic keys, but no positional structureNo

Use nested unpacking when the structure is simple and you want to avoid boilerplate. Use a namedtuple or dataclass when you need to pass the structure around or add behavior. For data that arrives as JSON or from an external API, dictionaries are often the default, and you can unpack them with .items() when iterating.

A practical rule: if you find yourself writing several lines of indexing to extract values, nested unpacking may improve readability. If the structure is deeply nested or the meaning of each field is not obvious, introduce named types instead.

Nested Unpacking with Dictionaries and Custom Objects

Nested unpacking is primarily for sequences. With dictionaries, iteration yields keys, not values. This pattern binds the inner dictionary's keys, not the stored values:

python
data = {"user": {"name": "Alice", "age": 30}} for key, (name, age) in data.items(): print(key, name, age) # user name age

If you need the stored values, use explicit key access:

python
for key, value in data.items(): print(key, value["name"], value["age"]) # user Alice 30

This is clearer than trying to force nested unpacking onto a dictionary.

Custom objects can support unpacking by being iterable, typically by implementing __iter__:

python
class Point: def __init__(self, x, y): self.x = x self.y = y def __iter__(self): yield self.x yield self.y p = Point(2, 3) x, y = p

If the order of yielded values is part of the class's contract, document it. If the object is not iterable, unpacking raises TypeError.

Nested unpacking is a useful tool for structured data when the shape is stable. It keeps assignments concise, makes mismatched data fail early, and works well with loops and record parsing. Keep patterns shallow and use named types when fields need documentation or behavior.

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.