Module 10 · Comprehensions and Advanced Iteration — topic 11 of 13
Generators
Generator functions that produce values one at a time with yield: how they pause and resume, infinite generators, reading data in pipelines, and why they are simpler than iterator classes.
Learning objectives
- Write generator functions
- Explain how a generator pauses and resumes
- Use generators for large or infinite sequences
Definition
A generator is a function that contains yield. Calling it returns a generator object (an iterator); each next() runs the function until the next yield, returns that value and pauses, keeping all local state until it is resumed.
Introduction
The Countdown iterator class needed three methods and a state variable. The generator version is four lines: a loop that yields each value. Python handles __iter__, __next__ and StopIteration for you.
Why it matters
Generators are the standard way to produce sequences lazily: reading big files, generating IDs, streaming API pages or building data pipelines.
Detailed explanation
Any function containing yield is a generator function. Calling it doesn't run the body; it returns a generator object.
Each next() resumes the body from where it last paused and runs until the next yield, which hands a value back and pauses again. Local variables keep their values between steps.
When the function body finishes (or hits return), the generator raises StopIteration automatically.
Generators can be infinite (while True: yield ...) because values are only produced when requested; combine them with itertools.islice or a break.
Like all iterators, a generator object is single-use. Call the generator function again to start over.
Syntax
- yield makes a function a generator.
- Calling it returns a generator object.
- Each next() resumes until the next yield.
Code examples
A generator function
generator [3, 2, 1] [5, 4, 3, 2, 1]
Pausing and resuming
created start 1 after first yield 2 end finished
More examples
Infinite generators and pipelines
['ORD0001', 'ORD0002', 'ORD0003'] Asha 1200 Meera 5400
Step-by-step explanation
- ids never ends, but islice takes just three values, so only three are ever computed.
- read_records yields one cleaned record at a time, skipping comments and blank lines.
- paid_totals consumes records and yields only paid ones — each stage handles one item before the next is read.
- The pipeline would work unchanged on a file object with millions of lines.
Expected output
Running “Infinite generators and pipelines” prints exactly:
Practical applications
- Reading log files lazily line by line.
- Paginating through API results.
- Generating test data or unique identifiers on demand.
Best practices
- Use generators instead of iterator classes.
- Build data pipelines from small generator functions.
- Bound infinite generators with islice or a break.
Common mistakes
Calling a generator and expecting it to run
Avoid
Prefer
Calling a generator function only creates the generator; the body runs when it is iterated.
Using return to produce values
Avoid
Prefer
return ends the function after the first value; yield produces each value in turn.
Important notes
- yield from other_iterable delegates to another iterable, yielding all its values.
Key takeaways
- A function with yield returns a generator object.
- It pauses at each yield and keeps its local state.
- Generators are lazy, single-use and can be infinite.
Try it yourself
- 1Write fibonacci() as an infinite generator and print the first 10 values.
- 2Write a generator that yields the lines of a list that contain a given keyword.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
10 questions cover the “Comprehensions and Advanced Iteration” module. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?
- ModerateWhat is printed?
- ModerateWhat is printed?