A lazy log pipeline
Add a fourth stage that upper-cases the messages. Nothing runs until list(messages) is called.
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
nothing has run yet: generator
messages: ['disk full', 'timeout']
any error? True
all non-empty? True
count of INFO: 3
total characters: 70