liveBook · Manning

Generator

As explained in Practices of the Python Pro

A generator is a Python construct that produces a sequence of values incrementally while preserving its execution state between requests.

A generator produces one value at a time, pausing until the next value is requested. Because it does not store every result together, it can reduce memory use when processing large sequences. section 4.2.3

The yield keyword returns a value and pauses execution, allowing the generator to continue preparing the next value afterward. A typical generator sets up its state, loops, yields each result, and updates that state. section 4.2.3

Squared values

def squares(items): for item in items: yield item ** 2 This produces squared values as they are requested instead of constructing a complete list first. section 4.2.3

How Practices of the Python Pro covers it

How deep it goes
Defines incremental production, explains yield-based pausing, and demonstrates a range-like implementation.
Examples
Uses range-like counting, squared-number generation, and chained generators to illustrate incremental computation and memory use.
What it assumes
Assumes basic Python iteration and data types while teaching yield and incremental state management.
What you can do after
Build it from scratch with yield-based loops and choose it over lists when all results are not needed at once.
How it connects
Connects generators with iteration, lists, range, yield, memory complexity, and performance testing.

Also explained in

Compare how 12 books explain generator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.