Sub topic 3
Scope, Laziness, and Readability in Comprehensions
Assume you know Python for loops, range, lists, dictionaries, sets, boolean expressions, and append. This chapter focuses on what comprehensions do beyond their basic syntax.
Scope: Why the Loop Variable Does Not Leak
In Python 3, a comprehension has its own scope. Its loop variable does not replace a variable with the same name outside the comprehension.
x = "outer"
squares = [x * x for x in range(3)]
print(squares) # [0, 1, 4]
print(x) # outerThe x inside the comprehension is local to that comprehension. This differs from a normal for loop:
x = "outer"
for x in range(3):
pass
print(x) # 2The loop variable in a normal loop remains available after the loop.
Generator Expressions: The Lazy Alternative
A list comprehension builds the entire list immediately. A generator expression produces values one at a time when another function requests them.
| Form | Main behavior | Typical use |
|---|---|---|
| `[n * n for n in numbers]` | Builds a list now | Need repeated access |
| `(n * n for n in numbers)` | Produces values lazily | Need one pass or less memory |
total = sum(n * n for n in range(1_000_000))
print(total)The generator does not create a million-item list first.
Common Pitfalls
{}creates an empty dictionary, not an empty set. Useset().- Use
[[0] * 3 for _ in range(2)]for independent inner lists.[[0] * 3] * 2repeats one list reference, so changing one row changes both. - Avoid side effects, such as printing or mutating unrelated data, inside a comprehension. A plain loop makes those actions clearer.
- In a dictionary comprehension, later values overwrite earlier values when keys repeat.
Reusing a Computed Value
Python 3.8 introduced the assignment expression, also called the walrus operator, :=. It lets a comprehension compute a value once and reuse it.
results = [y for n in range(5) if (y := n * n) > 3]
print(results) # [4, 9, 16]Use this sparingly. The extra syntax can make a short transformation harder to scan.
Readability: When a Plain Loop Is Better
Prefer a comprehension when it contains one clear transformation and, at most, a simple filter. Prefer a loop when the logic has several conditions, multiple actions, error handling, or meaningful side effects.
Exercise
Which form should you use to sum squares from 1 to 1,000,000 without building a list?
Show answer
Use sum(n * n for n in range(1, 1_000_001)), a generator expression passed to sum.