Generators & Iterators

Difficulty: Advanced

Question

What are generators in Python? How are they different from regular functions and from building a list?

Answer

A generator is a function that contains yield. Calling it does not run the body; it returns a generator object that produces values lazily, one per next() call, pausing at each yield and resuming exactly where it left off. Because only one value exists at a time, a generator can process a 10 GB log file or an infinite stream in constant memory, where a list would have to hold everything at once.

The iterator protocol underneath

Every for loop in Python uses two methods:

Writing an iterator class by hand means managing state in attributes and raising StopIteration yourself. A generator function gives you all of that for free: Python saves the local variables and the instruction pointer in the generator's frame between calls. A generator is both an iterable and its own iterator, which is why it can be consumed only once.

Generator vs regular function vs list

AspectRegular function returning a listGenerator
When work happensAll at once, before returningOn demand, per next()
MemoryO(n), whole list in RAMO(1) for the generator state
ReuseIterate as many times as you likeExhausted after one pass
Indexing, len()SupportedNot supported
Infinite sequencesImpossibleNatural

Use a list when you need random access, multiple passes or len(). Use a generator when you stream data once: reading files, paging through an API, or chaining transformations.

yield, generator expressions and yield from

Pipelines in real systems

Generators shine as stages in a pipeline, the same idea as Unix pipes. A Swiggy order-analytics job might read lines from a file, parse JSON, filter failed orders and sum amounts in paise, with each stage a generator. Nothing is materialised in between, so memory stays flat no matter how big the input is. Django's QuerySet.iterator(), csv.reader, os.walk and file objects all expose this lazy style.

Gotchas interviewers probe

How a for loop drives a generator. The generator runs only until the next yield, then hands control back to the caller.
  1. for loop → Generator: next(): start running body
  2. Generator → for loop: yield 1 and pause
  3. for loop → Generator: next(): resume after yield
  4. Generator → for loop: yield 2 and pause
  5. for loop → Generator: next(): resume again
  6. Generator → for loop: body ends, StopIteration

Code examples

Generator function vs list version

import sys

def squares_list(n):
    return [i * i for i in range(n)]

def squares_gen(n):
    for i in range(n):
        yield i * i          # pause here, resume on next()

lst = squares_list(1_000_000)
gen = squares_gen(1_000_000)
print(sys.getsizeof(lst) > 8_000_000)   # list holds a million pointers
print(sys.getsizeof(gen) < 500)         # generator holds only its frame

g = squares_gen(3)
print(next(g), next(g), next(g))
print(list(g))   # already exhausted

The list stores every element up front; the generator stores only its paused state. Once consumed, a generator yields nothing more.

Lazy pipeline over a large log file

import json

def read_lines(path):
    with open(path, encoding="utf-8") as f:   # closed when generator finishes
        yield from f

def parse(lines):
    for line in lines:
        yield json.loads(line)

def failed_orders(records):
    return (r for r in records if r["status"] == "FAILED")

def total_paise(path):
    records = parse(read_lines(path))
    return sum(r["amount_paise"] for r in failed_orders(records))

# Works the same for 10 lines or 10 crore lines: one record in memory at a time.
# print(total_paise("orders.jsonl"))

Each stage pulls one item at a time from the previous stage, so memory use stays constant regardless of file size.

Key points

Common follow-up questions

Interview tips

Concepts covered

Generators, yield, Iterator Protocol, Lazy Evaluation, yield from, Generator Expressions

More Python Interview questions