Explain Python generators and how yield saves memory
Quick Summary: A Python generator is a lazy iterator function using yield that produces one value at a time on demand and suspends its execution frame between next() calls, keeping memory constant O(1) instead of loading entire datasets into RAM.
Direct Interview Answer
Unlike a normal function returning a materialized list of millions of items, calling a function containing yield immediately returns a generator object without executing the body yet.
Each call to next(gen) resumes execution up to the next yield, preserves local variables and instruction pointer on pause, and raises StopIteration when exhausted.
Detailed Technical Explanation
Remember that generators are single-pass iterators: once consumed, iterating over the same generator instance again yields zero items unless you recreate it. You can also write concise generator expressions with parentheses like (row.strip() for row in file).
Practical Walkthrough
Streaming large log entries in O(1) memory with yield.
def filter_error_lines(lines):
for line_no, text in enumerate(lines, start=1):
if "ERROR" in text:
yield line_no, text.strip()
sample_logs = ["INFO ok", "ERROR db timeout", "INFO retry", "ERROR auth failed"]
for no, msg in filter_error_lines(sample_logs):
print(f"Line {no}: {msg}")
Line 2: ERROR db timeout Line 4: ERROR auth failed
Real-World Production Use Case
Streaming 10 GB CSV exports, database cursor batches, and LLM token Server-Sent Events (SSE) in FastAPI without triggering OOM crashes.
Common Interview Mistakes to Avoid
- Iterating over an already-exhausted generator twice and getting empty results silently.
- Wrapping a huge generator inside list(gen), immediately defeating O(1) lazy memory usage.