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.

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:
point = (1, (2, 3))
x, (y, z) = point
print(x, y, z) # 1 2 3The 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.
nested = [1, [2, 3], 4]
a, (b, c), d = nested
print(a, b, c, d) # 1 2 3 4If 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.
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:
a, (b, *c), d = [1, [2, 3, 4], 5]
print(a, b, c, d) # 1 2 [3, 4] 5Here 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:
record = ["2024-01-01", "web", "auth", "login"]
timestamp, *tags, message = recordThis 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.
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:
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.
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():
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:
first, *rest = large_listThis 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.
| Approach | Best for | Unpacking support |
|---|---|---|
| Nested unpacking | Fixed, short structures | Native |
| Indexing | Dynamic access, but verbose | No |
| namedtuple | Named fields plus tuple behavior | Yes |
| dataclass | Mutable, complex objects with methods | No (unless custom) |
| Dictionary | Dynamic keys, but no positional structure | No |
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:
data = {"user": {"name": "Alice", "age": 30}}
for key, (name, age) in data.items():
print(key, name, age) # user name ageIf you need the stored values, use explicit key access:
for key, value in data.items():
print(key, value["name"], value["age"]) # user Alice 30This is clearer than trying to force nested unpacking onto a dictionary.
Custom objects can support unpacking by being iterable, typically by implementing __iter__:
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 = pIf 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 toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.