List comprehensions
A list comprehension builds a new list by evaluating an expression for each item in an iterable, optionally skipping items with if. It replaces a short for loop that only appends.
Detailed Explanation
The pattern "make an empty list, loop, append" is so common that Python gave it a form. [price * 100 for price in prices] walks prices, multiplies each value, and collects the results. The loop variable exists only inside the comprehension in Python 3. The source iterable is not modified.
A filter clause drops items: [sku for sku in skus if sku.startswith("EU-")]. You can add more for clauses for nested loops, and more if clauses for extra filters. The clauses run left to right, like nested for/if statements. Two fors over length-n inputs produce up to n² results, so the compact syntax does not change the cost.
The expression can be any expression: a function call, a ternary, a tuple. It cannot be a statement. If you need two lines of work per item, use a for loop. Comprehensions are for mapping and filtering, not for hiding side effects. A comprehension whose expression is print(x) or cache.put(x) is a loop in costume.
[func(x) for x in items] calls func once per kept item and stores every return value. If you only want the side effects, write a loop. If you only want the first match, write a for with break, or use next((x for x in items if pred(x)), None) with a generator expression.
Generator expressions use parentheses instead of brackets and produce values lazily. A list comprehension is eager: it builds the whole list before anything else runs. On a large input that you will iterate once, the generator form saves memory. On a small input you will reuse, the list is clearer.
Nested comprehensions get unreadable quickly. One filter and one map is the sweet spot. When the expression needs a name for an intermediate value, the walrus operator can bind it, or you can switch to a loop. Readability is part of the feature's contract.
Code Examples
prices = [9.5, 4.0, 12.0]
cents = [int(price * 100) for price in prices]
print(cents) # [950, 400, 1200]
eu = [sku for sku in ["EU-1", "US-2", "EU-3"] if sku.startswith("EU-")]
print(eu) # ['EU-1', 'EU-3']# Nested for clauses are nested loops, left to right.
grid = [(row, col) for row in range(2) for col in range(3)]
print(grid) # [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
# A generator expression is lazy; list() forces it.
squares = (n * n for n in range(5))
print(next(squares)) # 0
print(list(squares)) # [1, 4, 9, 16]# The loop name does not leak in Python 3.
print([n for n in range(3)]) # [0, 1, 2]
# print(n) # NameErrorCommon Gotchas
A comprehension is not a loop for side effects
building a list of `None`s from `append` or `print` wastes memory and hides the mutation. Use `for`.
Nested `for` clauses are quadratic
`[x + y for x in left for y in right]` has `len(left) * len(right)` items. That is easy to miss because it fits on one line.
The expression is evaluated for every kept item
an expensive call belongs in a helper you can cache, or in a loop where you can skip work.
`if` in a comprehension is a filter, not a ternary
`[x if x else 0 for x in nums]` always produces a value. `[x for x in nums if x]` drops falsy items.