Planet Python
Follow
Rodrigo Girão Serrão: Unpacking inside comprehensions
Python 3.15 introduces the ability to use the asterisk operator for unpacking within list comprehensions. This new feature simplifies flattening nested lists, allowing for more concise code. For instance, a list of lists can be flattened by unpacking each sublist directly into the comprehension. Previously, achieving the same result required a nested list comprehension, which was more verbose. The unpacking syntax mirrors the structure of equivalent nested for loops. The unpacking operator works not only with list comprehensions but also with set comprehensions, dictionary comprehensions, and generator expressions. This article details the new syntax and provides alternatives for older Python versions. It is part of a series celebrating Python 3.15 features with clear explanations and examples. The goal is to make new functionalities accessible without needing to comb through official changelogs. Readers can subscribe to receive this free educational email series.