Skip to content

Lesson 9 of 52Collections

Comprehensions

Build lists, dicts and sets in one readable line, filter as you go, and use generator expressions to save memory.

16 min read0/6 questions

A huge amount of everyday code is "take this collection, transform or filter each item, and collect the results". Python has a dedicated syntax for that, the comprehension, and experienced Python developers use it all the time. You will read comprehensions in nearly every codebase and interviewers expect you to write them fluently. Knowing when not to use one matters just as much.

From loop to comprehension

Here is a loop that builds a list of squares:

squares = []
for n in range(1, 6):
    squares.append(n * n)

A list comprehension says the same thing in one expression: what to produce, then where it comes from.

Python
squares = [n * n for n in range(1, 6)]print(squares) names = ["ada", "sam", "priya"]print([name.title() for name in names])print([len(name) for name in names])
Output
Press Run (⌘ Enter) to see what happens.

Read it left to right as a sentence: "n * n, for each n in range(1, 6)". The brackets mean the result is a list. Comprehensions are usually a little faster than the equivalent append loop too, because the looping happens inside the interpreter's C code.

Filtering with if

Add if condition at the end to keep only some items.

[n * n for n in nums if n % 2 == 0]
1
0
2
1
3
2
4
3
5
4
6
5
result = []

Walk nums left to right. For each item, test the if first.

1/5
Python
words = ["apple", "", "kiwi", " ", "fig"]clean = [w for w in words if w.strip()]print(clean) prices = [12, 250, 40, 999]print([p for p in prices if 20 <= p <= 500])
Output
Press Run (⌘ Enter) to see what happens.

Filter vs choose

There are two places an if can go, and they do different jobs:

  • [x for x in nums if x > 0]: the if at the end filters. Items can be dropped.
  • [x if x > 0 else 0 for x in nums]: a conditional expression at the front chooses a value. Every item produces something.
Predict the outputPython

What does this print?

nums = [3, -1, 4, -2]
print([n for n in nums if n > 0])
print([n if n > 0 else 0 for n in nums])
Need a nudge? Hints walk you through it.

Dict and set comprehensions

Swap the brackets and you get other collections. Curly braces with key: value make a dict comprehension; curly braces with a single expression make a set comprehension.

Python
names = ["ada", "sam", "priya"]lengths = {name: len(name) for name in names}print(lengths) prices = {"tea": 3, "cake": 5, "pie": 4}on_sale = {item: price * 0.8 for item, price in prices.items() if price >= 4}print(on_sale) emails = ["A@x.com", "b@y.com", "a@x.com"]domains = {e.lower().split("@")[1] for e in emails}print(sorted(domains))
Output
Press Run (⌘ Enter) to see what happens.

There is no tuple comprehension. Parentheses do something different, which you will see in a moment.

Quick check
What does {w[0] for w in ["apple", "avocado", "banana"]} produce?
Need a nudge? A hint rules out a wrong answer.

Nested comprehensions

A comprehension can have more than one for. The clauses read in the same order as nested loops: outer first, inner second.

Python
grid = [[1, 2, 3], [4, 5, 6]] flat = [x for row in grid for x in row]print(flat) # the loop version, in the same order:flat2 = []for row in grid: for x in row: flat2.append(x)print(flat2 == flat) # a comprehension inside a comprehension builds a grid safelyboard = [[0] * 3 for _ in range(2)]board[0][0] = 1print(board)
Output
Press Run (⌘ Enter) to see what happens.

That last one fixes the shared-row trap from the lists lesson: the inner [0] * 3 runs once per row, so each row is a fresh list.

Put it in order4 steps

Rewrite [(r, c) for r in range(2) for c in "ab" if c != "b"] as loops. Put the lines in order (outermost first).

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Generator expressions: lazy comprehensions

Put a comprehension in parentheses and you get a generator expression. Instead of building the whole list in memory, it produces items one at a time, on demand. That is called being lazy.

Python
import sys as_list = [n * n for n in range(1_000_000)]as_gen = (n * n for n in range(1_000_000)) print(sys.getsizeof(as_list), "bytes for the list")print(sys.getsizeof(as_gen), "bytes for the generator") print(sum(n * n for n in range(1_000_000))) # no extra parentheses needed in a call
Output
Press Run (⌘ Enter) to see what happens.

When you only need to loop once (to sum, max, any, all, or write to a file), a generator saves memory. The catch: a generator can be consumed only once. After that it is empty. You will see much more of this in the iterators and generators lesson.

Predict the outputPython

What does this print?

g = (x for x in range(4))
print(sum(g))
print(sum(g))
Need a nudge? Hints walk you through it.

Comprehension scope

A for loop's variable lives on after the loop: write for y in range(4): pass and y is still 3 afterwards. A comprehension is different. Its loop variable belongs to the comprehension's own scope, so it never leaks out and never overwrites a name you already had. In Python 2 list comprehensions did leak, which is why you may still see old code that carefully avoids reusing names.

Since Python 3.12 (PEP 709), CPython inlines list, dict and set comprehensions into the surrounding function instead of creating a hidden function object for each one. That made them faster, but the visible rules did not change: the loop variable is still private. Generator expressions are still separate function-like objects, because they have to pause.

There is one rule about evaluation that matters in practice: the first iterable (the one after the first in) is evaluated immediately, in the surrounding scope. Everything else (the expression, the if, any later for) runs inside the comprehension's scope. For generator expressions, that is why a bad first iterable fails straight away while an error in the expression only appears when you consume it.

The class-body trap

Names defined in a class body are not visible inside nested scopes, and the comprehension's body counts as nested. So a comprehension in a class body can read class attributes in its first iterable, but not anywhere else. The error looks baffling the first time you see it:

Python
x = "outer"squares = [x * x for x in range(4)]print(x) # the comprehension's x did not leak for y in range(4): passprint(y) # a for loop's variable does class Pricing: VAT = 0.2 bands = [10, 20, 30] gross = [b * 2 for b in bands] # bands is the first iterable: fine try: with_vat = [b * (1 + VAT) for b in bands] except NameError as err: print("NameError:", err) # VAT is in the expression: not visible print(Pricing.gross) VAT = 0.2 # the fix: a module constant class Fixed: bands = [10, 20, 30] with_vat = [round(b * (1 + VAT), 2) for b in bands] print(Fixed.with_vat)
Output
Press Run (⌘ Enter) to see what happens.

You hit this most in config classes, enums and test classes that build a lookup table from other class attributes. The fixes: move the constant to module level, compute the value in a classmethod or after the class body, or pass it through the first iterable. The same scope rule explains why methods must write self.VAT rather than VAT, which Scope and Closures covers in depth.

Predict the outputPython

What does this print?

x = 10
total = sum(x for x in range(4))
print(total, x)
Need a nudge? Hints walk you through it.

The walrus operator in comprehensions

A common pattern is "compute something for each item, keep it only if it is useful". Without help you end up computing it twice: [f(x) for x in xs if f(x)]. If f parses text, runs a regex or hits a cache, that doubles the work.

The assignment expression := (nicknamed the walrus, added in 3.8) binds a name inside an expression. Use it in the if clause and reuse the name in the output expression:

Python
import re lines = ["id=17 ok", "no id here", "id=4 retry", "id=x bad"]ID = re.compile(r"id=(\d+)")ids = [int(m.group(1)) for line in lines if (m := ID.search(line))]print(ids) def parse_price(text): try: return float(text) except ValueError: return None raw = ["3.50", "free", "12", "", "0"]prices = [p for t in raw if (p := parse_price(t)) is not None]print(prices) readings = [12, 15, 31, 18, 40]if any((hot := r) > 30 for r in readings): print("first reading over 30:", hot)
Output
Press Run (⌘ Enter) to see what happens.

Three details matter:

  • Write is not None when zero is a valid value. if (p := parse_price(t)) would silently drop the price 0.0, because it is falsy. That bug ships to production regularly.
  • The walrus name leaks on purpose. Unlike the loop variable, a name bound with := inside a comprehension is bound in the enclosing scope. That is what makes the any(...) trick work: any stops at the first match, and hot holds the item that matched. A short-circuiting search with a witness, in one line.
  • It has limits. You cannot use := to rebind the comprehension's own loop variable ([i := 0 for i in range(3)] is a SyntaxError), and you cannot use it in a comprehension inside a class body.

The parentheses around (m := ...) are required in most positions. If you find yourself writing two walruses in one comprehension, write a loop instead. For the regex side of this example, see Regular Expressions.

Predict the outputPython

What does this print?

data = [3, 0, 5]
out = [y for x in data if (y := x * 2)]
print(out, y)
Need a nudge? Hints walk you through it.

Unpacking in comprehensions (3.15)

Flattening a list of lists is so common that Python 3.15 (PEP 798) lets you write it directly with * and ** in the output position. The browser here runs 3.14, so this block is for reading:

rows = [[1, 2], [3], [4, 5]]
flat = [*row for row in rows]              # [1, 2, 3, 4, 5]
unique = {*row for row in rows}            # a set of every item
dicts = [{"a": 1}, {"b": 2}, {"a": 3}]
merged = {**d for d in dicts}              # {'a': 3, 'b': 2}, later wins
lazy = (*row for row in rows)              # a generator of every item

On 3.14 and earlier, these are the equivalents you will keep seeing in real code:

Python
from itertools import chain rows = [[1, 2], [3], [4, 5]]print([x for row in rows for x in row]) # nested for: works everywhereprint(list(chain.from_iterable(rows))) # lazy, and the fastest for long inputs dicts = [{"a": 1}, {"b": 2}, {"a": 3}]print({k: v for d in dicts for k, v in d.items()})
Output
Press Run (⌘ Enter) to see what happens.

The new syntax reads like the [*a, *b] unpacking you already know from lists. Until your project's minimum version is 3.15, keep using the nested for or chain.from_iterable; a file containing the new form fails to parse on older versions, so not even an if sys.version_info check can protect it. chain.from_iterable is covered in functools, itertools and operator.

Performance: comprehension vs loop vs map

People say comprehensions are "faster". They are, but by less than folklore suggests, and the reason matters more than the number. Measure it with timeit:

Python
import timeit setup = "nums = list(range(10_000))"candidates = { "for + append": """out = []for n in nums: out.append(n * 2)""", "comprehension": "[n * 2 for n in nums]", "map + lambda": "list(map(lambda n: n * 2, nums))", "map(str, ...)": "list(map(str, nums))", "[str(n) ...]": "[str(n) for n in nums]",} for label, stmt in candidates.items(): best = min(timeit.repeat(stmt, setup=setup, number=100, repeat=5)) print(f"{label:<15} {best * 10:7.3f} ms per run")
Output
Press Run (⌘ Enter) to see what happens.

On CPython 3.14 on a laptop, the comprehension came out about 10 to 20 percent faster than the append loop, and map with a lambda about twice as slow as either. Your numbers will differ, and the browser runs a WebAssembly build that is slower overall, but the ranking is stable. Here is why:

  • The append loop looks up out.append and calls it on every item. The comprehension uses a dedicated bytecode instruction to add each item, so it skips that lookup and call.
  • map with a lambda calls a Python function for every item, and Python function calls are relatively expensive. It loses to a comprehension that does the work inline.
  • map with a built-in like str or int has no Python-level function to call, so it is roughly equal to, and often slightly faster than, the comprehension.

The practical rule: write the comprehension because it is clearer, not because it is faster. A 15 percent gain on a loop that takes a millisecond is invisible next to a database query. If a loop really is a bottleneck, profile first (Profiling and Making Python Fast shows how), and the fix is usually a better algorithm or a set instead of a list, not a different loop syntax.

When not to use a comprehension

Comprehensions are for building a collection. They get hard to read quickly. Switch back to a regular loop when:

  • There are more than two for clauses, or the condition needs and/or chains.
  • You need statements: try/except, print, several steps per item.
  • You are running it only for side effects. [print(x) for x in items] builds a useless list of Nones; write a for loop.

A good rule: if you cannot read the comprehension out loud as one sentence, it should be a loop.

ChallengeEasy

Squares of evens

Write squares_of_evens(nums) that returns the squares of the even numbers, in their original order. Try to do it in one line with a list comprehension.

squares_of_evens([1, 2, 3, 4])  →  [4, 16]
squares_of_evens([1, 3])        →  []
Python
def squares_of_evens(nums: list[int]) -> list[int]: # [expression for item in iterable if condition] pass
ChallengeEasy

Word lengths

Write word_lengths(words) that returns a dict mapping each word to its length. Use a dict comprehension.

word_lengths(["hi", "there"])  →  {"hi": 2, "there": 5}
Python
def word_lengths(words: list[str]) -> dict[str, int]: # {key: value for item in iterable} pass
Key terms
list comprehension
[expr for x in iterable if cond]: builds a list in one expression.
dict comprehension
{k: v for x in iterable}: builds a dict.
set comprehension
{expr for x in iterable}: builds a set, so duplicates collapse.
generator expression
(expr for x in iterable): lazy, produces items on demand and can be consumed once.
lazy evaluation
Computing values only when they are asked for, instead of all up front.
comprehension scope
The private scope a comprehension's loop variable lives in, so it never leaks. Only the first iterable is evaluated outside it.
assignment expression
name := value, the walrus operator. Binds a name inside an expression; in a comprehension it binds in the enclosing scope.