5.5. Star Comprehension

  • Since Python 3.15, you can use the star operator in comprehensions to unpack elements from iterables.

  • PEP 798 - Unpacking in Comprehensions

5.5.1. List Comprehension

  • [*row for row in rows] - unpack elements from iterable into a new list

>>> data = [
...     [1, 2, 3],
...     [4, 5, 6],
...     [7, 8, 9],
... ]
>>>
>>> [*row for row in data]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

5.5.2. Dict Comprehension

  • {**row for row in rows} - unpack elements from iterable into a new dictionary

>>> DATA = [
...     {'username': 'alice', 'password': 'secret'},
...     {'firstname': 'Alice', 'lastname': 'Apricot'},
...     {'is_active': True, 'is_staff': True, 'is_admin': True},
... ]
>>>
>>>
>>> {**row for row in DATA}
{'username': 'alice', 'password': 'secret', 'firstname': 'Alice', 'lastname': 'Apricot', 'is_active': True, 'is_staff': True, 'is_admin': True}

5.5.3. Assignments