Generators

Introduction to generators and yield

You already know how to build a list inside a function and return it. Generators are functions that hand back values one at a time, on demand, using yield. This lesson shows what changes when you swap return for yield.


So far, when a function had to return many values, you built a list inside the function and returned the whole thing.

Here is a function that returns the first three squares as a list:

Python
Output

That works for three values. But imagine the function had to produce a million. The full list would sit in memory all at once, even if the caller only needs the values one at a time.

Generators solve this. They produce values on demand, one by one, without ever building the full collection. The keyword is yield.

Any function that contains yield is a generator function:

Python

The squares example, rewritten as a generator:

Python
Output

Each yield pauses the function. The next request picks up where it left off, with all the local state intact:

Python
Output

What will be the output?

Python

Calling a generator function does not run it. It returns a generator object:

Python
Output

Use next() to ask the generator for one value at a time:

Python
Output

This is where generators pay off. The loop below would build a list of a billion numbers and crash on memory. The generator version pulls just the first three and stops, never computing the rest:

Python
Output

Pass the generator to list() to collect every value at once:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python