Python developers frequently work with nested lists, sets, and dictionaries when processing API responses, database records, configuration files, and application data. Combining these structures often requires nested loops, additional comprehensions, or helper functions.
Python already supports unpacking with the and * operators in list, set, and dictionary displays. However, before Python 3.15, developers could not use this unpacking syntax directly at the beginning of a comprehension expression.
Python 3.15 introduces unpacking in comprehensions through PEP 798. This feature allows developers to flatten multiple iterables, combine sets, merge dictionaries, and create generator expressions with shorter and more readable code.
For example, a list of lists can now be flattened using a single expression:
lists = [[1, 2], [3, 4], [5]]
result = [*items for items in lists]
print(result)
Output:
[1, 2, 3, 4, 5]
This syntax provides a direct alternative to nested comprehensions and utilities such as itertools.chain().
In this article, you will learn how unpacking works in Python 3.15 comprehensions, how to use it with lists, sets, dictionaries, and generators, and how to apply it to practical data-processing scenarios.
What Is Unpacking in Comprehensions?
Unpacking means extracting elements from an iterable or mapping and placing them into another collection.
Python has supported unpacking in collection displays for several versions.
For example, you can combine multiple lists using the * operator:
first = [1, 2]
second = [3, 4]
third = [5, 6]
result = [*first, *second, *third]
print(result)
Output:
[1, 2, 3, 4, 5, 6]
Similarly, dictionaries can be combined using **:
defaults = {"theme": "light", "language": "English"}
overrides = {"theme": "dark"}
result = {**defaults, **overrides}
print(result)
Output:
{'theme': 'dark', 'language': 'English'}
Before Python 3.15, this syntax was available in collection displays, but not directly in list, set, and dictionary comprehensions.
Python 3.15 extends the syntax so that developers can unpack each iterable or mapping while processing a collection.
The feature supports:
- List comprehensions using *.
- Set comprehensions using *.
- Dictionary comprehensions using **.
- Generator expressions using and *.
- Asynchronous generator expressions with unpacking.
The change is defined by PEP 798 and is available in Python 3.15 and later.
Flattening Lists With Unpacking
Flattening a list means converting a nested list into a single list containing the elements from its inner lists.
Consider the following example:
numbers = [
[1, 2, 3],
[4, 5],
[6, 7, 8]
]
Before Python 3.15, developers commonly used a nested comprehension:
numbers = [
[1, 2, 3],
[4, 5],
[6, 7, 8]
]
result = [
number
for group in numbers
for number in group
]
print(result)
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
Python 3.15 allows a shorter expression:
numbers = [
[1, 2, 3],
[4, 5],
[6, 7, 8]
]
result = [*group for group in numbers]
print(result)
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
The expression *group unpacks the elements of each inner iterable into the resulting list.
This makes the intention easier to understand when the goal is simply to combine multiple iterables.
Working With Empty and Mixed Iterables
Unpacking works with any iterable, not only lists.
For example, a collection can contain lists, tuples, strings, and other iterable objects.
items = [
[10, 20],
(30, 40),
range(50, 53)
]
result = [*item for item in items]
print(result)
Output:
[10, 20, 30, 40, 50, 51, 52]
An empty iterable contributes no elements.
groups = [
[1, 2],
[],
[3, 4],
[]
]
result = [*group for group in groups]
print(result)
Output:
[1, 2, 3, 4]
This behavior is useful when processing API responses or database results where some groups may contain no records.
However, every expression following * must evaluate to an iterable. Attempting to unpack an integer or another non-iterable value raises a TypeError.
Combining Sets With Unpacking
Set comprehensions can also use unpacking.
A set stores unique values, so duplicate elements are automatically removed.
Consider a collection of sets:
groups = [
{1, 2, 3},
{3, 4, 5},
{5, 6, 7}
]
Before Python 3.15, developers could combine these sets using a nested comprehension:
result = {
value
for group in groups
for value in group
}
print(result)
Python 3.15 provides a shorter alternative:
groups = [
{1, 2, 3},
{3, 4, 5},
{5, 6, 7}
]
result = {*group for group in groups}
print(result)
Output:
{1, 2, 3, 4, 5, 6, 7}
The unpacking expression extracts values from each set and inserts them into the resulting set.
Because sets do not preserve duplicate values, repeated elements appear only once.
Combining Tags From Multiple Sources
Consider an application that receives tags from different services.
service_tags = [
{"python", "backend", "api"},
{"backend", "database"},
{"cloud", "python"}
]
all_tags = {*tags for tags in service_tags}
print(all_tags)
The result contains the unique tags from all three sources.
This approach is useful when combining categories, permissions, feature flags, or identifiers from multiple collections.
Remember that set elements must be hashable. If an inner iterable contains unhashable values such as lists or dictionaries, inserting those values into a set raises a TypeError.
Merging Dictionaries With Unpacking
Dictionary unpacking is another important part of Python 3.15 comprehension improvements.
Consider a list of dictionaries containing configuration values:
configurations = [
{"theme": "light", "language": "English"},
{"theme": "dark"},
{"language": "French", "timezone": "UTC"}
]
Before Python 3.15, developers could merge these dictionaries using a loop:
result = {}
for configuration in configurations:
result.update(configuration)
print(result)
Python 3.15 allows the same operation using a dictionary comprehension:
configurations = [
{"theme": "light", "language": "English"},
{"theme": "dark"},
{"language": "French", "timezone": "UTC"}
]
result = {**configuration for configuration in configurations}
print(result)
Output:
{
'theme': 'dark',
'language': 'French',
'timezone': 'UTC'
}
The ** operator unpacks each mapping into the resulting dictionary.
When multiple dictionaries contain the same key, the value from the last occurrence wins.
This follows the normal dictionary unpacking behavior.
Understanding Duplicate Dictionary Keys
Duplicate keys are important when combining configuration data from multiple sources.
Consider this example:
defaults = {"timeout": 30, "retries": 3}
environment = {"timeout": 60}
user_settings = {"retries": 5}
configurations = [
defaults,
environment,
user_settings
]
result = {**item for item in configurations}
print(result)
Output:
{'timeout': 60, 'retries': 5}
The dictionary comprehension processes the mappings from left to right.
The environment configuration replaces the default timeout, and the user settings replace the default retry count.
This makes dictionary unpacking useful for configuration merging and override systems.
Processing API Response Metadata
Suppose an application receives metadata from multiple services.
Each service returns a dictionary containing information such as request ID, region, status, and processing time.
service_metadata = [
{
"request_id": "REQ-101",
"region": "Asia",
"status": "success"
},
{
"request_id": "REQ-102",
"region": "Europe",
"status": "success"
},
{
"request_id": "REQ-103",
"region": "Asia",
"status": "failed"
}
]
combined_metadata = {
**metadata
for metadata in service_metadata
}
print(combined_metadata)
Because request_id is repeated, the resulting dictionary contains the last request's value for that key.
For this reason, dictionary unpacking should only be used when later values are intentionally allowed to override earlier ones.
If the application needs to preserve every request, use a list of dictionaries instead of merging them into one dictionary.
Using Unpacking in Generator Expressions
Python 3.15 also extends unpacking to generator expressions.
Generator expressions produce values lazily instead of creating the complete result immediately.
Consider a list of lists:
groups = [
[1, 2, 3],
[4, 5],
[6, 7]
]
You can create a generator that yields the elements from each inner iterable:
result = (*group for group in groups)
for value in result:
print(value)
Output:
1
2
3
4
5
6
7
The generator expression does not create the complete flattened list immediately.
It produces values as the generator is consumed.
You can convert the generator into a list when needed:
groups = [
[1, 2, 3],
[4, 5],
[6, 7]
]
result = list(*group for group in groups)
print(result)
Output:
[1, 2, 3, 4, 5, 6, 7]
For large datasets, generators can help avoid allocating a complete intermediate list.
However, lazy evaluation does not automatically make every operation memory-efficient. The consumer still determines whether values are processed one at a time or stored in another collection.
Using Unpacking With Asynchronous Generator Expressions
Python 3.15 extends the feature to asynchronous generator expressions.
This is useful when an application processes data from asynchronous iterators, such as records received from an asynchronous service or streaming source.
Consider an asynchronous function that returns groups of values.
import asyncio
async def get_groups():
yield [1, 2]
yield [3, 4]
yield [5, 6]
async def main():
values = (
*group
async for group in get_groups()
)
async for value in values:
print(value)
asyncio.run(main())
The asynchronous generator expression unpacks each group and yields its individual elements.
This is equivalent in behavior to iterating through each asynchronous result and then iterating through the elements inside that result.
The feature is useful when working with asynchronous data pipelines, streaming responses, and background processing.
It is important to distinguish between the asynchronous iteration that retrieves each group and the normal iteration that unpacks the elements of that group.
Comparing Python 3.15 Unpacking With Older Approaches
Python already provides several ways to flatten iterables and combine dictionaries. Python 3.15 adds a more direct syntax to comprehensions.
The following table compares common approaches.
Operation | Traditional approach | Python 3.15 approach |
|---|
Flatten lists | Nested list comprehension | [*items for items in groups] |
Combine sets | Nested set comprehension | {*items for items in groups} |
Merge dictionaries | Loop with update() | {**item for item in mappings} |
Flatten generator output | Nested generator expression | (*items for items in groups) |
Combine asynchronous iterables | Nested async generator expression | (*items async for items in groups) |
The traditional approaches remain valid. The new syntax provides another option when the primary goal is unpacking each item from a collection.
Unpacking Versus itertools.chain()
The itertools module has long provided a reliable way to flatten iterables.
For example:
from itertools import chain
groups = [
[1, 2],
[3, 4],
[5, 6]
]
result = list(chain.from_iterable(groups))
print(result)
Python 3.15 offers an alternative:
groups = [
[1, 2],
[3, 4],
[5, 6]
]
result = [*group for group in groups]
print(result)
Both approaches flatten one level of nested iterables.
The choice depends on readability, project conventions, and whether an iterator or a concrete collection is required.
itertools.chain.from_iterable() remains useful in existing code and in scenarios where its iterator behavior fits the surrounding pipeline.
Practical Example: Processing Product Categories
Consider an e-commerce application that receives product categories from multiple services.
Each service returns a list of categories. The application needs to combine these values before generating a report.
category_results = [
["Electronics", "Computers"],
["Home", "Furniture"],
["Electronics", "Accessories"]
]
all_categories = [
*categories
for categories in category_results
]
print(all_categories)
Output:
[
'Electronics',
'Computers',
'Home',
'Furniture',
'Electronics',
'Accessories'
]
If the application needs unique categories, use a set comprehension:
unique_categories = {
*categories
for categories in category_results
}
print(unique_categories)
This removes duplicate category names.
If the application needs to preserve the original order while removing duplicates, a different approach is required because sets do not guarantee the same insertion-order behavior as lists.
For example:
unique_categories = list(
dict.fromkeys(all_categories)
)
print(unique_categories)
Output:
[
'Electronics',
'Computers',
'Home',
'Furniture',
'Accessories'
]
This example demonstrates how Python 3.15 unpacking can simplify the initial flattening operation while existing collection tools remain useful for additional requirements.
Best Practices for Using Unpacking in Comprehensions
Use Unpacking When Flattening One Level
The new syntax is particularly useful when each item contains another iterable and the goal is to combine its elements into one result.
For deeply nested structures, consider whether a recursive solution or a dedicated flattening function would communicate the intent more clearly.
Understand the Source Data
Unpacking works with iterables and mappings, but not every object can be unpacked.
Validate or normalize external data before processing it when the source may contain unexpected values.
Be Careful With Dictionary Key Collisions
When multiple dictionaries contain the same key, the last value replaces earlier values.
This is useful for configuration overrides, but it can also cause data loss if duplicate keys are not expected.
Choose Sets When Uniqueness Matters
Set comprehensions automatically remove duplicate values.
However, sets do not preserve the same ordering guarantees as lists. Use a list when order and duplicates matter.
Use Generators for Lazy Processing
Generator expressions are useful when processing large collections without creating an intermediate list.
However, remember that a generator is consumed as it is iterated. If you need to traverse the results multiple times, materialize them into an appropriate collection.
Avoid Overly Complex Comprehensions
A shorter expression is not always easier to maintain.
If a comprehension contains complicated conditions, transformations, and multiple levels of iteration, a normal loop may be easier for other developers to understand.
Check the Python Version
Unpacking in comprehensions is a Python 3.15 feature.
Applications running on Python 3.14 or earlier cannot use this syntax. Check the interpreter version and deployment environment before adopting it.
Common Mistakes When Using Unpacking
Unpacking a Non-Iterable Value
The * operator requires an iterable.
This example raises a TypeError:
values = [10, 20, 30]
result = [*value for value in values]
Each value is an integer, and integers are not iterable.
Use unpacking only when the expression produces an iterable object.
Assuming Dictionary Unpacking Preserves Duplicate Values
A dictionary cannot contain multiple independent values for the same key.
When the same key appears in multiple mappings, later values replace earlier ones.
If every value must be preserved, use a list of dictionaries or group the values under a shared key.
Using Sets When Order Matters
Set comprehensions are designed for unique elements, not ordered output.
If the application requires a stable sequence, use a list comprehension or another ordered collection.
Expecting Recursive Flattening
The expression below flattens only one level:
values = [
[1, 2],
[3, [4, 5]]
]
result = [*group for group in values]
print(result)
The result is:
[1, 2, 3, [4, 5]]
The inner list remains nested.
For recursive flattening, use an explicit recursive function or another suitable data-processing approach.
Using Python 3.15 Syntax in Older Environments
A project may run locally with Python 3.15 but deploy to a server using an older interpreter.
Make sure the production environment, CI pipeline, local development environment, and container images use a compatible Python version.
Advantages and Limitations
Advantages | Limitations |
|---|
Reduces nested comprehension syntax | Requires Python 3.15 or later |
Makes iterable flattening more direct | Flattens only one level at a time |
Supports list, set, and dictionary comprehensions | Dictionary key collisions can replace earlier values |
Supports generator expressions | Generators are consumed during iteration |
Supports asynchronous generator expressions | Requires an asynchronous iteration context |
Provides an alternative to itertools.chain() | Does not replace every use case of itertools |
Keeps related collection operations concise | Complex expressions may become harder to read |
Conclusion
Python 3.15 introduces unpacking in comprehensions through PEP 798, making it easier to combine multiple iterables and mappings in a single expression.
Developers can use to flatten lists and combine sets, while * can merge multiple dictionaries. The same feature extends to generator expressions and asynchronous generator expressions.
This improvement is particularly useful when processing API responses, combining configuration data, collecting categories, and building data-processing pipelines.
The new syntax does not replace traditional loops, itertools, or other collection utilities. Instead, it provides a concise alternative when unpacking is the main operation.
Use it when it improves readability, pay attention to duplicate dictionary keys and collection ordering, and make sure the application runs on Python 3.15 or later.
Join the conversation! Your thoughts help the community grow.