Python 3.15+Lists (list)construct
Unpacking * and ** in comprehensions
comprehension
[*xs for xs in lists] flattens nested collections into one, and {**d for d in dicts} merges dictionaries. Replaces a double loop and itertools.chain.
Syntax
[*it for it in iterables]
{*s for s in sets}
{**d for d in dicts}
(*it for it in iterables)
A star at the start of a comprehension's expression means “spread out all the elements”, as in [*a, *b]: [*row for row in matrix] equals [x for row in matrix for x in row] but reads without the second for. It works for lists, sets, generator expressions, and with ** for dicts; when merging dicts, duplicate keys are overwritten by the last value, as in {**a, **b}. Only one level is unpacked: [*xs for xs in [[1, [2]]]] gives [1, [2]]. Before 3.15 this is a SyntaxError, so code for older versions keeps the double loop or itertools.chain.from_iterable.
Examples
lists = [[1, 2], [3, 4], [5]]
print([*xs for xs in lists]) # → [1, 2, 3, 4, 5]
print({*s for s in [{1, 2}, {2, 3}]}) # → {1, 2, 3}
dicts = [{'a': 1}, {'b': 2}, {'a': 3}]
print({**d for d in dicts}) # → {'a': 3, 'b': 2} — последний ключ побеждает
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy