What is a generator and how does it differ from a list?medium

Type
conceptual
Topic
generator
Frequency
common
Tags
generator, yield, iterator, lazy evaluation
Answer

A generator lazily produces values using yield, keeping only its current state in memory rather than materialising all values at once.

Explanation

Generators are useful for streams, large files, and data pipelines where building a full list would be expensive or impossible. A generator function suspends at each yield and resumes on the next next() call. Generators implement the iterator protocol automatically — they have both __iter__ and __next__. yield from delegates to a sub-iterator, flattening it and enabling composable generator pipelines without additional nesting.

Follow-upHow is a generator expression different from a list comprehension?
Follow-upWhat does yield from do?
Follow-upWhy can't you iterate over a generator twice?