By the end of this lesson
Read a simple comprehension and compare an eager list with a generator.
Before you start
- Python 3.12 or a compatible newer Python 3 interpreter; no external packages.
- Complete lesson 9 in this route, or be comfortable with its examples.
Three words to know
- Comprehension
- A compact expression that builds a collection from iteration.
- Iterable
- An object you can iterate over.
- Generator
- An iterator that yields values on demand.
1. Keep transformations small
A comprehension combines the value expression with a loop and optionally a filter. Start by reading the loop and filter, then ask what value is produced. When the rule needs several decisions or error handling, an ordinary loop is usually easier to debug.
numbers = [1, 2, 3, 4]
even_squares = [n * n for n in numbers if n % 2 == 0]
print(even_squares)
What you should see · example output
[4, 16]
2. Generators are consumed
Parentheses create a generator expression rather than a list. It computes values as requested and remembers its current position. Once exhausted it does not restart. Build a new generator or keep a list if you need repeated passes.
values = (n * 2 for n in range(3))
print(list(values))
print(list(values))
What you should see · example output
[0, 2, 4] []
3. Smaller memory does not mean unlimited input
A generator may avoid storing an entire intermediate list, but the source may still be huge and the work may still take a long time. The final project reads bounded input deliberately. List and dictionary comprehensions are tools for clarity, not a reason to remove validation or size limits.
YOUR TURN
A small check before you continue
Build a list containing the lengths of ["read", "test", "ship"]. Then explain whether a generator can be iterated twice to get the same items.
Show a suggested answer
The list comprehension [len(word) for word in words] produces [4, 4, 4]. A particular generator is consumed; construct another one or materialise a list for repeated traversal.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
