Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.3 — Generator Expressions and Lazy Pipelines
Python · Example 2 of 2

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.

01

Use a generator expression with sum to add up the squares of the numbers 1 to 10.

02

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.

03

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

01

What is the difference between a list comprehension and a generator expression, and when do you choose each?

02

Why are generator expressions a good fit for any and all?

03

What is a lazy pipeline, and what are its benefits and its risks?

04

A function returns (line for line in f). Why might a caller be surprised the second time they loop over it?

05

Which part of a generator expression is evaluated immediately, and which part lazily? Why does it matter?

A lazy log pipeline
Sign in to run this example in your browser.

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