Python 3.15 Unpacking Comprehensions Tutorial: Flatten Lists and Merge Dictionaries
Learn how Python 3.15 unpacking comprehensions flatten nested lists, combine sets, generate values lazily, and merge dictionaries with practical examples and compatibility guidance.
On this page
If you have ever flattened a list of lists with a nested comprehension or merged several dictionaries in a loop, Python 3.15 gives you a shorter way to express that work. Its new unpacking comprehensions let you use * to expand iterables and ** to expand dictionaries directly inside list, set, dictionary, and generator comprehensions. The feature arrived with Python 3.15.0, released on October 9, 2026, and is particularly useful when transforming collections of data without adding extra loops.
Check that your Python version supports unpacking comprehensions
Before changing your code, confirm that you are running Python 3.15 or later. Unpacking comprehensions are specified by Python Enhancement Proposal 798 (PEP 798), which extends syntax that already existed in ordinary list and dictionary displays. Earlier Python versions do not recognize this new comprehension syntax, so code using it will fail to parse rather than silently falling back to the old behavior.
python --version
On Windows, the Python launcher can help you select a particular installed version:
py -3.15 --version
If the command reports Python 3.15, create a file named unpacking_demo.py for the examples below. You do not need an external package because the feature is part of the Python language itself. If you maintain a project that supports older Python releases, keep the version requirement in mind before adopting the syntax in shared code.
Flatten nested lists with the new star expression
Suppose an application receives groups of product identifiers from several categories and needs one flat list. A traditional nested comprehension can do the job, but it expresses the operation by iterating over every group and then every element inside it. Python 3.15 allows the leading expression of a comprehension to be starred, making the expansion explicit at the point where each group is processed.
groups = [
["A101", "A102"],
["B201"],
["C301", "C302", "C303"],
]
product_ids = [*group for group in groups]
print(product_ids)
The result is ['A101', 'A102', 'B201', 'C301', 'C302', 'C303']. Each iteration takes one group, expands its elements, and adds them to the resulting list. An empty group contributes nothing, which is useful when some categories have no products. The operation preserves the order of elements and groups, so it is suitable when the original sequence matters.
The equivalent traditional comprehension is [item for group in groups for item in group]. Both approaches flatten one level of nesting, not every level recursively. If an element inside a group is itself a list, that inner list remains an element in the result unless you explicitly process it too.
Choose between list, set, and generator comprehensions
The same unpacking idea can be used with different comprehension types, but the resulting data structure changes what happens to the values. A list keeps order and duplicate elements, a set removes duplicates, and a generator produces values lazily as they are requested. This means you can choose a result based on the task rather than writing a separate flattening algorithm for every collection type.
groups = [
[1, 2, 2],
[2, 3],
[4, 4],
]
flat_list = [*group for group in groups]
unique_values = {*group for group in groups}
value_stream = (*group for group in groups)
print(flat_list)
print(unique_values)
print(list(value_stream))
The list contains every value in its original order, including repeated numbers. The set contains only unique values, and its iteration order should not be relied upon as a display order. The generator expression does not immediately build a complete list; it yields values as the program consumes them. That can reduce the need to allocate a large intermediate collection when the next stage can process items incrementally.
There is an important distinction between unpacking an iterable and recursively flattening data. The starred expression expands the iterable returned for the current group by one level. If a group contains strings, each string can be expanded into individual characters, and if a group contains a non-iterable value, Python raises a TypeError. Make sure the values you unpack have the shape your application expects.
Merge configuration dictionaries with double-star unpacking
Dictionary merging is another practical use for PEP 798. Applications often combine default settings, environment-specific options, and user overrides. Previously, developers might use a loop with dict.update() or construct a new dictionary using a separate unpacking expression. Python 3.15 lets a dictionary comprehension expand each mapping directly, while preserving the normal rule that later values replace earlier values when keys collide.
defaults = {
"theme": "light",
"timeout": 30,
"retries": 2,
}
environment = {
"theme": "dark",
"region": "eu-west",
}
user_options = {
"timeout": 60,
}
configurations = [defaults, environment, user_options]
settings = {**config for config in configurations}
print(settings)
The resulting dictionary is {'theme': 'dark', 'timeout': 60, 'retries': 2, 'region': 'eu-west'}. The default configuration is processed first, the environment configuration overrides its theme, and the user options replace the timeout. This order makes the precedence visible in the input list, which is easier to review than a series of hidden mutations spread across a function.
The expression expects dictionary-like mappings that can be expanded with **. It does not recursively merge nested dictionaries. If both configurations contain a key named database whose value is itself a dictionary, the later value replaces the earlier one as a whole. Applications that need deep merging must implement that policy explicitly rather than assuming unpacking will combine nested structures.
Use a generator when you do not need every value at once
For large datasets, creating a full flattened list can consume substantial memory before the application begins processing its contents. A generator expression gives the same expansion behavior without immediately storing all the results. This is useful when values are consumed by a loop, a pipeline, or another function that accepts an iterable.
def process_ids(groups):
for product_id in (*group for group in groups):
print(f"Processing {product_id}")
groups = [
["A101", "A102"],
["B201", "B202"],
]
process_ids(groups)
The generator yields each identifier as the loop requests it, so the program does not need to create one large flattened list first. In real applications, this can be helpful when processing database batches, log records, or incoming chunks of data. The example still stores the original groups in memory, however, and it does not make the source data itself lazy. The memory benefit depends on how the input is produced and how the generator is consumed.
Understand when the new syntax is clearer than the old one
Unpacking comprehensions are not automatically better than every existing technique. For a single short list, ordinary unpacking such as [*first, *second] may already be the clearest choice. For a complicated transformation that filters, validates, or changes each individual item, a conventional nested comprehension or an explicit loop can communicate the logic more clearly. The new syntax is most valuable when the main operation really is expanding each iterable or mapping into a combined result.
It is also worth considering compatibility. A library that supports Python 3.14 and older cannot put Python 3.15-only syntax in a module that those interpreters must import, even if the relevant function is rarely called. If you need to support multiple versions, use the established nested comprehension, loop, or itertools.chain.from_iterable() approach in shared code, and reserve the new syntax for projects whose minimum supported version includes Python 3.15.
Test the edge cases before using it in production
Empty iterables, duplicate values, conflicting dictionary keys, and unexpected input types are the cases most likely to reveal a mistaken assumption. An empty group should add no values to a flattened list, while a set should eliminate duplicates and a dictionary merge should use the value from the last mapping containing a repeated key. If your data comes from an external source, validate its shape before unpacking it; concise syntax does not replace input validation.
For a small regression test, compare the new expression with the older implementation on representative input and assert that both produce the same expected result. Include empty groups and repeated values, and explicitly test dictionary precedence. When reviewing a pull request, the key question is not whether the new expression uses fewer characters, but whether a future maintainer can immediately see how the collection is being transformed. If the expansion is the central operation, Python 3.15's syntax is a useful addition; if the logic is more involved, clarity still matters more than brevity.
Share this post
Written by



