Python theorytheory 0/50 · 0%
Collections · easy

20. List, dict, and set comprehensions

Concise syntax for building collections from iterables.

Comprehensions build a new collection in one expression, generally faster and more readable than an equivalent loop with `.append()`.

python
squares = [n**2 for n in range(10) if n % 2 == 0]
lookup = {name: len(name) for name in ["eth", "sol", "avax"]}
uniq = {c for c in "mississippi"}

Nested comprehensions are possible but should be used sparingly for readability:

python
flat = [x for row in matrix for x in row]

Generator expressions use parentheses instead of brackets and produce values lazily: `sum(n * n for n in range(1000000))` avoids building an intermediate list.

Check your understanding

  1. 1. What does `[n for row in matrix for x in row]`-style nesting do (order of `for`)?

  2. 2. How do you write a generator expression instead of a list comprehension?

  3. 3. Why prefer a generator expression for `sum(...)` over a list comprehension?