Difficulty: Advanced
What are generators in Python? How are they different from regular functions and from building a list?
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.
Every for loop in Python uses two methods:
iter(obj) calls obj.__iter__() and returns an iterator.next(it) calls it.__next__() and returns the next value, or raises StopIteration when done.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.
| Aspect | Regular function returning a list | Generator |
|---|---|---|
| When work happens | All at once, before returning | On demand, per next() |
| Memory | O(n), whole list in RAM | O(1) for the generator state |
| Reuse | Iterate as many times as you like | Exhausted after one pass |
Indexing, len() | Supported | Not supported |
| Infinite sequences | Impossible | Natural |
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.
(x * x for x in nums) is the lazy cousin of a list comprehension. sum(x * x for x in nums) never builds the list.yield from sub_gen() delegates to another iterable and forwards values, send() and exceptions. It is the clean way to flatten nested generators.gen.send(v) (the yield expression evaluates to v). This was the basis of old-style coroutines before async/await, and it still powers contextlib.contextmanager.StopIteration and becomes the result of yield from.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.
g = (x for x in range(3)); list(g); list(g) gives [0, 1, 2] and then [].next(), not at the call.StopIteration that leaks out of a generator body is converted to RuntimeError. Use return to finish.open() in with inside the generator, and call close() if you abandon it early.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.
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.
Generators, yield, Iterator Protocol, Lazy Evaluation, yield from, Generator Expressions