Generator
PronunciationJEN-er-ay-ter
Definition
A generator is a function that produces values one at a time using yield, pausing between values instead of building the whole list in memory.
Where you hear it
In Python code that reads large files or streams, in performance reviews about memory use, and in explanations of lazy evaluation.
Examples
We use a generator to read the log file line by line.
The generator is infinite, so take only the first ten values.
The generator yields each row of the export, so the whole file never sits in memory.
Common mistake
Treating a generator like a list. You cannot index it or measure its length, and it can be read only once.
Don't confuse with
A list comprehension, which builds the full list immediately. A generator expression has the same shape but produces items lazily.
Say it at work
- In a meeting or chat
Make it a generator so we never hold the whole file in memory.
- In an email or ticket
This pipeline is lazy: each stage is a generator.
Keep exploring
More in Programming Fundamentals