Command Palette

Search for a command to run...

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

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.

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?

List comprehension versus generator expression
Sign in to run this example in your browser.

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