What are Generators and the yield Keyword?
Learn what Python generators and the yield keyword are, how lazy evaluation saves memory, with clear code examples and common interview questions and answers.
Expected Interview Answer
A generator is a function that produces a sequence of values lazily, one at a time, using the yield keyword instead of return, so values are computed on demand rather than all stored in memory at once.
When a function contains yield, calling it returns a generator object without running the body. Each call to next() runs the function until the next yield, hands back that value, and freezes the function's state until resumed. This lets you iterate over huge or infinite sequences with constant memory, because only the current value exists at any moment.
- Memory efficient — values produced one at a time
- Can represent infinite or very large sequences
- Lazy evaluation defers work until needed
- Cleaner code than manual iterator classes
- Composable in pipelines with other generators
AI Mentor Explanation
A generator is like a bowler delivering one ball at a time in an over rather than throwing all six at once. The over pauses between deliveries, keeps its state (balls bowled, current score), and resumes only when the umpire signals the next ball — nothing is precomputed or stored ahead.
Step-by-Step Explanation
Step 1
Write yield instead of return
Any function containing at least one yield statement becomes a generator function.
Step 2
Call the function
Calling it does not run the body — it returns a generator object in a paused state.
Step 3
Advance with next()
Each next() runs the body until the following yield, returning that value and freezing state.
Step 4
Iterate with a loop
A for loop calls next() automatically and stops cleanly when StopIteration is raised.
Step 5
Exhaustion
When the function returns or ends, StopIteration signals the generator is used up and cannot restart.
What Interviewer Expects
- Clear difference between yield and return
- Understanding of lazy evaluation and memory savings
- Knowing a generator is a kind of iterator
- Awareness that generators are single-use
- Ability to give a practical use case like streaming a large file
Common Mistakes
- Thinking the function body runs when the generator is created
- Trying to reuse an exhausted generator without recreating it
- Confusing generators with regular lists that hold all values
- Forgetting a generator has no len() and cannot be indexed
- Believing yield returns control permanently instead of pausing state
Best Answer (HR Friendly)
“A generator is a special Python function that gives back values one at a time using yield, instead of building a whole list at once. It saves memory because it only produces the next value when you ask for it, which is great for large or streaming data.”
Code Example
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
gen = count_up_to(3)
print(next(gen)) # 1
print(next(gen)) # 2
for value in count_up_to(3):
print(value) # 1, 2, 3def read_lines(path):
with open(path) as f:
for line in f:
yield line.strip()
# Processes one line at a time, never loading the whole file
for line in read_lines('big.log'):
if 'ERROR' in line:
print(line)Follow-up Questions
- What is the difference between a generator and a list comprehension?
- How does a generator expression differ from a generator function?
- What does the send() method do on a generator?
- How do yield from and delegation work?
- Why can you iterate over a generator only once?
MCQ Practice
1. What does calling a generator function return?
Calling a generator function returns a generator object without executing the body; execution begins only when you advance it.
2. What happens when a generator has no more values to yield?
When the function ends, the generator raises StopIteration, which a for loop catches to stop cleanly.
3. Which is the main advantage of generators over lists?
Generators produce values on demand, so they hold only the current value in memory instead of the whole sequence.
Flash Cards
What keyword makes a function a generator? — yield — any function containing yield becomes a generator function.
How does yield differ from return? — yield pauses the function and preserves state; return ends it. yield can fire many times.
Are generators reusable? — No — a generator is exhausted after one full iteration and must be recreated to run again.
Why are generators memory efficient? — They compute and hold only the current value, using lazy evaluation instead of storing all values.