In short
Writing iterator classes is a lot of boilerplate. Generators let you write the same thing as a simple function with yield, and they can process files bigger than your RAM without breaking a sweat.
A generator function uses yield to produce values one at a time and pauses between them, so it uses very little memory. Generator expressions like (x * x for x in nums) do the same in one line.

Think of it like this
A dosa counter, not a buffet
A buffet cooks everything up front and fills the table. A dosa counter makes one dosa when you're ready, hands it over, and waits for the next person. A generator is the dosa counter: each yield serves one value and pauses until you ask for the next.
Watch it happen
Pausing and resuming at yield
next()
1/5The loop asks for a value. The function body starts running.
The big ideas
What you need to know
yield pauses
Any function with yield becomes a generator. Calling it returns a generator object; no code runs until you iterate.
Tiny memory use
Only one value exists at a time. Summing a billion squares with a generator uses almost no memory.
Generator expressions
(x * x for x in nums) is like a list comprehension with round brackets, but lazy.
Pipelines
Chain generators: read lines, filter them, transform them, each step passing one item at a time.
See it in code
Walk through the code
1def read_orders(path: str):2 with open(path, encoding="utf-8") as f:3 for line in f:4 yield line.strip().split(",")5 6def big_orders(rows, minimum: float):7 for order_id, city, amount in rows:8 if float(amount) >= minimum:9 yield order_id, city, float(amount)10 11def fib():12 a, b = 0, 113 while True:14 yield a15 a, b = b, a + b16 17gen = fib()18print([next(gen) for _ in range(8)]) # [0, 1, 1, 2, 3, 5, 8, 13]19 20squares = (n * n for n in range(1_000_000))21print(sum(squares)) # computed one at a time22 23# pipeline: nothing is read until the loop starts24# for order in big_orders(read_orders("orders.csv"), 5000):25# print(order)1/6Yields one parsed line at a time. A 5 GB file never sits in memory all at once.
A file-reading generator, a filtering generator, an infinite Fibonacci generator and a generator expression.
Save yourself the pain
Common mistakes
Oops
Writing return value inside a generator to send back results.
Do this instead
Use yield for each value. A return just ends the generator.
Oops
Calling len() on a generator.
Do this instead
Generators don't know their length. Convert with list() if you really need it, or count while looping.
Oops
Using [x for x in huge] when you only need to loop once.
Do this instead
Use a generator expression (x for x in huge) or pass it directly: sum(x for x in huge).
Your mission
Log file scanner
Quick check
What does calling a generator function like fib() return immediately?
Go deeper
- 1Write a generator that reads a huge log file line by line.
- 2Compare the memory use of a list comprehension and a generator expression for a million numbers.
- 3Chain two generators together to filter and then transform data.
More topics at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.