Lesson 10 of 10

Lazy generators

Goal

One value on demand, not a whole list

01

Explanation

A regular function computes everything and returns it all at once. A function that contains yield becomes a generator: every time it reaches yield, it hands over a value and pauses right there, and it doesn't continue until you ask for the next value.

When you call it, not a single line of it runs. You just get a generator object, which you can ask for one value with next(gen), or for every value to the end with for or list(). This is called lazy evaluation, and it's what lets you read a file with a million lines one line at a time without loading it all into memory.

You can chain generators into a pipeline where each stage takes a generator and returns a generator, and nothing is computed until the last stage asks for its values. The trap is that a generator can only be consumed once. Loop over it a second time and you get nothing, with no error to warn you.

02

Your task

Write two generators. The first, parse(lines), yields (name, amount) from every non-empty line, with the amount as an integer. The second, large(orders, limit), yields the orders whose amount is limit or more. Then chain them like this: big = list(large(parse(log), 100)).

Checks

5 checks
  1. parse and large are generators
  2. parse yields the name and an integer amount and skips empty lines
  3. large yields the orders at or above the limit
  4. big is a list with the whole pipeline's result
  5. The pipeline is lazy and next reads no more than it needs
main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.