Skip to main content
Python Intermediate Practical Coding Topic: Iterators & Memory Efficiency

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.

Written by Ravi Shankar Mishra (Founder & Lead Systems Architect, MockAttempt Academy) Reviewed by MockAttempt Engineering Editorial Desk
Last verified:

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.

Code Example — PYTHON
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}")
Expected Output / Verification
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.
Topics: #python #generators #yield #memory
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.