Generator expression
- Python course
- Beginner
- Lesson 63/116
- 5 min
Learn generator expressions with (x for x in xs).
Generator expression
A generator expression is a comprehension written with parentheses; it is a one-shot producer:
gen = (n * n for n in [1, 2, 3])
print(list(gen)) # [1, 4, 9]A generator does not store the list in memory; it produces items on demand. This makes it memory-friendly for big data. Functions like list(), sum(), max() accept a generator.
Lazy evaluation
A generator produces items only when they are requested; this behavior is called lazy evaluation. Functions like sum() and max() consume the generator:
total = sum(n * n for n in [1, 2, 3])
# 14A generator is consumed once; calling list(gen) again gives an empty list. So convert and store it if you need it twice.
Practice Sum squares with a generator
Assign to total a generator expression that sums n * n for each n in [1, 2, 3, 4], using sum(). Then print print(total).
Starter code
# Sum squares with a generatorSample solution
total = sum(n * n for n in [1, 2, 3, 4])
print(total)Expected output
30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the generator expression
gen = (n * n for n in ____)
gen = (n * n for n in [1, 2, 3])
Explanation: The source is a list; the outer parens mark a generator.
2 What is the difference between a generator and a list comprehension?
- List is in memory, generator is lazy Correct answer
- List uses parens, generator uses braces
- List is slower, generator is faster
- They are the same thing
Explanation: A list stores all items in memory; a generator produces lazily.
3 Match the types
| Term | Meaning |
|---|---|
[n for n in x] |
List |
{n for n in x} |
Set |
{n: n for n in x} |
Dict |
(n for n in x) |
Generator |