Build a list with a comprehension
A list comprehension says *a new value for every item* in one expression. It is the the Collection Algorithms module transform loop without the plumbing.
- Read
[expression for name in items]as the loop it replaces - Choose each new value with a conditional expression inside the comprehension
- Recognise when a comprehension is the wrong tool: when the point is a side effect such as printing
In the Collection Algorithms module every transform had the same three lines of plumbing: labels = [], then for minutes in runtimes:, then labels.append(…) inside the loop. Only one part changed from problem to problem: the value you appended.
A list comprehension keeps only the part that matters. [expression for name in items] reads *the expression, for each name in items*. Python runs the same loop, collects one value per item, and gives you the finished list.
Run each example to see what it prints. Running examples doesn't count toward progress.
runtimes = [95, 110, 128, 86] labels = [f"{minutes // 60}h {minutes % 60}m" for minutes in runtimes] print(labels) print(runtimes)
The order of the words is fixed: the value first, then for. Writing the loop first, the way a for statement starts, is a syntax error, so nothing in the program runs.
runtimes = [95, 110] labels = [for minutes in runtimes: minutes // 60] print(labels)
The expression can be anything that produces a value: arithmetic on a field, a method call, or a choice. A conditional expression (a if test else b, from the Conditional Logic module) in front of the for picks one of two values for each item. Every item still produces exactly one value, so the result is as long as the input.
def profit_millions(movies): return [(m["revenue_usd"] - m["budget_usd"]) / 1000000 for m in movies] def verdicts(movies): return ["hit" if m["revenue_usd"] > m["budget_usd"] else "flop" for m in movies] movies = [ {"title": "Glass Echo of Glass", "budget_usd": 33000000, "revenue_usd": 132300000}, {"title": "Glass Horizon on Fire", "budget_usd": 23300000, "revenue_usd": 9400000}, {"title": "Wild Archive", "budget_usd": 29600000, "revenue_usd": 46400000}, ] print(profit_millions(movies)) print(verdicts(movies))
When to use it: when each new value depends only on its own item: a converted reading, a field pulled out of every record, a label chosen per row. Mistakes to avoid: writing a comprehension only to *do* something, such as printing, instead of to *build* a list. print returns None, so [print(t) for t in titles] prints the titles and then leaves you a list of Nones. A plain for loop says what you mean there.
[expression for name in items]builds one new value per item, in order. It replaces the empty-list, loop, append pattern.- A conditional expression in front of
forchooses each value; every item still produces one. - Use a comprehension to build a list, not to print or to change other variables.
- Next: the same idea with
key: value, to build a dictionary in one expression.