Iterators & Generators
Lesson opener
In one line: An iterator produces the next item when asked. A generator writes that iterator with yield.
Why it matters: Northline's nightly SKU file can be larger than the laptop should hold at once. The ETL job only needs one row at a time. Building a list of every row first is a choice, not a requirement of the loop. Figures are illustrative. The samples below are two rows, so the tests stay small.
Before this lesson: Loops and functions. Decorators are not required.
What you will be able to do
- Use
iterandnext, and stop onStopIteration. - Write a generator with
yieldand a generator expression. - Explain why a generator is single-pass.
- Keep a streaming transform from materialising the whole file.
Prerequisites
Python 3.12. Iterator is defined in https://docs.python.org/3/glossary.html#term-iterator. Generator is defined in https://docs.python.org/3/glossary.html#term-generator. yield is specified in https://docs.python.org/3/reference/expressions.html#yield-expressions. Generator expressions are in https://docs.python.org/3/reference/expressions.html#generator-expressions.
Ask for the next item
Plain English: iter(obj) asks obj for an iterator. next(iterator) asks for one item. When the iterator is finished it raises StopIteration. A for loop does those two steps and catches StopIteration for you.
A generator function contains yield. Calling it does not run the body. It returns a generator object. The body runs up to the next yield when you call next, then pauses. A generator expression such as (int(q) for q in qtys) is the same idea in one line. It is not a tuple. A tuple would use parentheses around a comma-separated list, or tuple(...).
Generators do not restart. A second loop over the same generator object sees nothing left. Create the generator again if you need another pass.
Teacher walkthrough: one stock row at a time
All figures are illustrative.
The extract has FX-100,80 and FX-200,10. The job yields pairs. It does not return a list from the generator function. The caller may list it when the sample is small.
- Split each line into SKU and quantity.
yieldthe pair.- Drive it with
nextuntilStopIteration. - Validation: the pairs match the file, and a second pass over the same generator is empty.
def parse(lines):
for line in lines:
sku, qty = line.split(",")
yield sku, int(qty)
lines = ["FX-100,80", "FX-200,10"]
gen = parse(lines)
assert next(gen) == ("FX-100", 80)
assert next(gen) == ("FX-200", 10)
try:
next(gen)
raise SystemExit("generator should be finished")
except StopIteration:
pass
assert list(gen) == []
assert list(parse(lines)) == [("FX-100", 80), ("FX-200", 10)]A generator expression sums quantities without building a list first. The generator function has to be in the same script, because each example runs on its own.
def parse(lines):
for line in lines:
sku, qty = line.split(",")
yield sku, int(qty)
qtys = (qty for _, qty in parse(["FX-100,80", "FX-200,10"]))
assert sum(qtys) == 90
assert sum(qtys) == 0A second workplace case
A counted iterator shows the protocol without yield. __iter__ returns the iterator. __next__ returns the next integer or raises StopIteration. Returning self means this object can be walked once.
class CountTo:
def __init__(self, n):
self.n = n
self.i = 0
def __iter__(self):
return self
def __next__(self):
if self.i >= self.n:
raise StopIteration
self.i += 1
return self.i
assert list(CountTo(3)) == [1, 2, 3]
assert list(CountTo(3)) == [1, 2, 3]
used = CountTo(2)
assert list(used) == [1, 2]
assert list(used) == []The second CountTo(3) is a new object, so it walks again. used is the same iterator, so the second list is empty.
Failure example: the totals were computed twice and the second pass was zero
Symptom: The ETL job printed 90 for the first total and 0 for the reconciliation total. The file had not changed.
Diagnosis: Both totals iterated the same generator object. The first sum exhausted it. The root cause is a single-pass iterator reused as if it were a list.
Correction: Call the generator function again for the second pass, or build a list once if you have measured that the file fits and you truly need random access. Do not assume yield rewinds.
Validation: Two calls to parse(lines) each sum to 90. One generator summed twice sums to 90 and then 0.
def parse(lines):
for line in lines:
sku, qty = line.split(",")
yield int(qty)
lines = ["FX-100,80", "FX-200,10"]
assert sum(parse(lines)) == 90
assert sum(parse(lines)) == 90
once = parse(lines)
assert sum(once) == 90
assert sum(once) == 0Guided practice: drop a blank SKU while streaming
Scenario: Lines are FX-100,80, ,5, and FX-200,10. Yield only rows whose SKU is non-blank. Figures are illustrative.
Hints:
- Do not
returna list from the generator if the point is to stream. - Skip a blank SKU with
continue. - Check
StopIterationor useliston a fresh generator.
Complete solution:
The generator yields two pairs. The blank line is skipped. The quantities are 80 and 10.
def kept(lines):
for line in lines:
sku, qty = line.split(",")
if sku == "":
continue
yield sku, int(qty)
rows = list(kept(["FX-100,80", ",5", "FX-200,10"]))
assert rows == [("FX-100", 80), ("FX-200", 10)]Independent practice
Pick one text extract you already loop over, even a short one.
Acceptance criteria:
- You write a generator that
yields one record at a time. - You show
nextandStopIterationon a two-item generator. - You show that summing the same generator twice does not repeat the total.
- You write one generator expression that transforms a field.
- You do not claim the sample's two rows prove a memory limit for a real file. They only prove the protocol.
Common mistakes
- Calling a generator function and expecting the body to finish immediately.
- Reusing one generator for a second report.
- Writing
(x for x in rows)and calling it a tuple. - Implementing
__next__without raisingStopIteration, so aforloop never ends.
Quick check
- What does calling a generator function return before any
yieldruns? - What does
nextraise at the end? - Why is the second
sumof the same generator 0 in this lesson? - How do you get a second pass?
- What is the difference between a generator expression and a list comprehension?
Answers:
- A generator object. The body has not run yet.
StopIteration.- The first
sumalready took every yielded item. - Call the generator function again, or store a sequence if you need one.
- The generator expression yields one item at a time. The list comprehension builds the whole list.
Quiz alignment
The quiz asks you to read yield, to exhaust an iterator, and to choose a fresh generator instead of a second pass over the same object.
Lesson summary
iter and next pull one item. yield pauses a function and turns it into an iterator. Generator expressions are single-pass. Create the generator again when the job must read the extract twice.
Bridge to the next lesson
The next lesson guarantees that a file or a session closes after the loop, including when the loop raises. Bring one resource you open and sometimes forget to close.