Flatten Iterables with Comprehension Unpacking
Core idea
Python 3.15 permits iterable unpacking in list, set and generator comprehensions and mapping unpacking in dict comprehensions. A leading * emits each element of the iterable selected by the loop; ** merges mapping entries into a dictionary. The same flattening on older versions uses nested loops or a nested comprehension. New syntax must be kept out of source files parsed by older interpreters.
batches = [[2, 4], [], [7]]print([*batch for batch in batches])configs = [{'mode': 'slow', 'retries': 1}, {'mode': 'fast'}]print({**cfg for cfg in configs})The empty batch contributes nothing. Later mappings override earlier values for matching keys; existing key position is preserved.
Documented expected output (target runtime not tested locally):
[2, 4, 7]{'mode': 'fast', 'retries': 1}Rewrite for Python 3.13
batches = [[2, 4], [], [7]]print([item for batch in batches for item in batch])merged = {}for cfg in [{'mode': 'slow', 'retries': 1}, {'mode': 'fast'}]: merged.update(cfg)print(merged)The older explicit implementation has the same observable behavior for these lists and dictionaries.
Expected output:
[2, 4, 7]{'mode': 'fast', 'retries': 1}Common mistake
Unpacking is one level, not recursive flattening. Each starred expression must produce an iterable; each double-starred expression must provide a mapping. For sets, duplicates collapse and display order is not a stable expected result. A version guard in the same file cannot prevent an older parser from rejecting new syntax.
Practice
On 3.15, flatten batches using a list comprehension, then a set comprehension with sorted output. Compare to 3.13 nested loops and test conflicting mapping keys. Record expected parser rejection on 3.13 separately.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Python 3.15 comprehension unpacking
Check your understanding of python 3.15 comprehension unpacking.
On Python 3.15 (documented expectation; target runtime not tested locally), what is printed?
print([*part for part in [[1], [2, 3]]])What is printed?
print([x for part in [[1], [2, 3]] for x in part])How are duplicate keys handled by mapping unpacking in a dict comprehension?
Why not hide new syntax behind an if-version check in the same file?