Club.noww.in
Learn how to use the unpacking operator inside list comprehensions.
Starting with Python 3.15, you can use the asterisk * to unpack inside list comprehensions:
nested = [[0, 1, 2], [3, 4], [], [5, 6, 7]] flattened = [*sublist for sublist in nested] print(flattened) # [0, 1, 2, 3, 4, 5, 6, 7]This new unpacking feature also works with set comprehensions, dictionary comprehensions, and generator expressions. This article explains the syntax, the alternatives in Python 3.14 or earlier, and shows real world example applications.
15 days of Python 3.15
To celebrate the release of Python 3.15, over the next 15 business days I'll be writing about a new 3.15 feature every day. Explained clearly and with examples so you don't have to sift through the changelog.
Subscribe to receive this free email series:
If you want, you can also check the schedule of the upcoming emails.
Unpacking inside a comprehension
If you have a nested list of lists, you can flatten them out by unpacking inside a comprehension:
nested = [[0, 1, 2], [3, 4], [], [5, 6, 7]] flattened = [*sublist for sublist in nested] print(flattened) # [0, 1, 2, 3, 4, 5, 6, 7]Before the unpacking syntax in 3.15, you'd have to write a nested list comprehension:
nested = [[0, 1, 2], [3, 4], [], [5, 6, 7]] flattened = [ element for sublist in nested for element in sublist ] print(flattened) # [0, 1, 2, 3, 4, 5, 6, 7]The structure of the nested list comprehension mirrors the structure of the equivalent nested for loop:
nested = [[0, 1, 2], [3, 4], [], [5, 6, 7]] for sublist in nested:...











English (US)