Intermediate Topic 36 of 54 Programming Fundamentals
Generators
Lazy functions that yield values on demand, pausing between them.
How it works
A generator function uses yield to produce a value and pause, resuming exactly where it left off on the next request. Its local state is preserved between yields, so it computes values lazily and uses constant memory regardless of sequence length. Generators are a convenient way to write iterators without managing state by hand.
Step-by-step walkthrough
- Calling the generator function returns an object without running the body.
- next() starts the body until the first yield.
- yield sends a value back and pauses with local state saved.
- The next call resumes just after the yield.
- Values are produced lazily so memory use stays small.
Where it is used
Streaming large datasets, reading big files, producing infinite sequences such as primes or IDs, building processing pipelines and implementing coroutine-style flows all use generators.
Common pitfall
Generators are one-shot and cannot be rewound, so iterating twice gives nothing the second time. Exceptions inside them surface only when the value is consumed, and resource cleanup depends on the generator finishing or being closed. Avoid converting them to lists when the data is large.
Where it fits in the course
Generators is topic 36 of 54 in Programming Fundamentals, rated Intermediate. It follows Iterators. The next topic is List Comprehensions.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Generators?
Where do people use Generators?
What is the most common mistake with Generators?
What should I learn before this topic?
How can I practice it?
Is Generators hard to learn?
How long does it take to learn Generators?
Which topics are related to Generators?
What should I study after Generators?
Related topics
- Iterators (Programming Fundamentals)
- List Comprehensions (Programming Fundamentals)
- Closures (Programming Fundamentals)
- Regular Expressions (Programming Fundamentals)
- Parser Generators (Languages & Compilers)