Use Unpacking in Comprehensions in Python 3.15

Use Unpacking in Comprehensions in Python 3.15

Comprehensions in Python provide a concise way to construct lists, sets, and dictionaries from existing iterables. Combining multiple collections into a single flat structure traditionally required nested iteration. Since Python 3.15, unpacking expressions can be used directly inside comprehensions, providing a simpler alternative for combining multiple iterables or dictionaries.

For example, several lists can be combined into one list using a nested comprehension. A similar pattern works for sets, while dictionaries can be merged by iterating over their key-value pairs.

lists = [[1], [2, 3, 4], [5, 6]]
flat = [v for sub in lists for v in sub]
print(flat)  # [1, 2, 3, 4, 5, 6]

sets = [{1}, {2, 3, 4}, {5, 6}]
flat = {v for sub in sets for v in sub}
print(flat)  # {1, 2, 3, 4, 5, 6}

dicts = [{'a': 1}, {'b': 2, 'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
flat = {k: v for sub in dicts for k, v in sub.items()}
print(flat)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}

Since Python 3.15, the * and ** unpacking operators can be used directly in comprehensions. The * operator expands each iterable into individual elements, while ** adds key-value pairs from each dictionary to the resulting dictionary. This makes collection merging easier to express without nested iteration.

lists = [[1], [2, 3, 4], [5, 6]]
flat = [*sub for sub in lists]
print(flat)  # [1, 2, 3, 4, 5, 6]

sets = [{1}, {2, 3, 4}, {5, 6}]
flat = {*sub for sub in sets}
print(flat)  # {1, 2, 3, 4, 5, 6}

dicts = [{'a': 1}, {'b': 2, 'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
flat = {**sub for sub in dicts}
print(flat)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}

Leave a Comment

Cancel reply

Your email address will not be published.