Python · Module 9 · Lesson 21 min read

Comprehensions & Generator Expressions

One-line collection builders

TypeSyntaxResult
List[x * 2 for x in nums]list
Set{x % 3 for x in nums}set (unique)
Dict{w: len(w) for w in words}dict
Generator(x * 2 for x in nums)lazy iterator

With conditions

  • Filter: [x for x in nums if x > 0]
  • Choose a value: ["even" if x % 2 == 0 else "odd" for x in nums]

Note where the if goes: at the end to filter, before for to choose.

Nested

[(r, c) for r in range(3) for c in range(3)] reads like nested loops, from left to right.

Generator expressions

Use parentheses for a lazy version that doesn't build a list in memory. Perfect inside sum(), any(), all(), max(): sum(x * x for x in range(1_000_000))

⚠️ Readability first: if a comprehension needs more than one line or several ifs, a normal loop is clearer.

▶️ Runs in the app.

Example

Python
nums = [3, -1, 4, -1, 5, 9]

squares = [x ** 2 for x in range(6)]
positives = [x for x in nums if x > 0]
labels = ["even" if x % 2 == 0 else "odd" for x in range(4)]
unique = {abs(x) for x in nums}
lengths = {w: len(w) for w in ["hi", "hello", "hey"]}

print(squares)     # [0, 1, 4, 9, 16, 25]
print(positives)   # [3, 4, 5, 9]
print(labels)      # ['even', 'odd', 'even', 'odd']
print(unique)      # {1, 3, 4, 5, 9}
print(lengths)     # {'hi': 2, 'hello': 5, 'hey': 3}

pairs = [(r, c) for r in range(2) for c in range(2)]
print(pairs)       # [(0, 0), (0, 1), (1, 0), (1, 1)]

print(sum(x * x for x in range(1_000_000)))   # no big list in memory
print(any(x < 0 for x in nums))               # True