List comprehension versus generator expression
Change 100_000 to 10 and run it. The generator stays tiny either way. The second sum prints 0 because the generator was used up.
A generator expression looks like a list comprehension with round brackets, but it produces values one at a time instead of building a list. Chained together, generator expressions make memory-friendly pipelines, and they pair well with any, all and sum.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Use a generator expression with sum to add up the squares of the numbers 1 to 10.
Given words = ["apple", "kiwi", "banana", "fig"], use any and all to print whether any word has more than 5 letters, and whether all words have at least 3 letters.
Build a two-stage pipeline over [" a ", "b", " ", "c "]: first strip every string, then keep only non-empty ones. Print the result as a list.
Explain it without notes
What is the difference between a list comprehension and a generator expression, and when do you choose each?
Why are generator expressions a good fit for any and all?
What is a lazy pipeline, and what are its benefits and its risks?
A function returns (line for line in f). Why might a caller be surprised the second time they loop over it?
Which part of a generator expression is evaluated immediately, and which part lazily? Why does it matter?
Expected output
list is big: True
generator is tiny: True
type: generator
sum from list: 333328333350000
sum from generator: 333328333350000
sum again: 0
first n with n*n > 5000: 71