Skip to content

Lesson 24 of 52Pythonic Python

Iterators and Generators

Understand how for loops really work, write lazy generators with yield, and use itertools like a pro.

26 min read0/9 questions

A for loop over a 20 GB log file should not need 20 GB of memory. Python handles this with iterators and generators: values produced one at a time, on demand. This is how files, range, zip, map, database cursors and streaming HTTP responses all work, and yield is a classic interview topic.

How a for loop really works

An iterable is anything you can loop over: lists, strings, dicts, files, ranges. An iterator is the object that actually walks through it, remembering where it is. The protocol has two parts:

  • iter(iterable) calls __iter__ and returns an iterator.
  • next(iterator) calls __next__ and returns the next value, or raises StopIteration when there are no more.

A for loop is just that, wrapped up for you:

for x in [10, 20]:
    print(x)
Python
nums = [10, 20, 30]it = iter(nums)print(next(it))print(next(it))print(list(it)) # the rest; the iterator remembers its positionprint(list(it)) # exhausted: nothing leftprint(next(it, "done")) # a default instead of StopIteration
Output
Press Run (⌘ Enter) to see what happens.

An iterator is single use. Once exhausted, it stays empty. A list is not an iterator; it is an iterable that hands out a fresh iterator every time you loop.

Predict the outputPython

What does this print?

squares = map(lambda n: n * n, [1, 2, 3])
print(sum(squares))
print(sum(squares))
Need a nudge? Hints walk you through it.

Generators: functions that pause

Writing a class with __iter__ and __next__ works but is verbose. A generator function is the shortcut: any function containing yield. Calling it does not run the body. It returns a generator object, an iterator. Each next() runs the body until the next yield, hands out that value, and pauses, keeping all its local variables. When the function returns, the generator raises StopIteration.

Python
def countdown(n): print(" starting") while n > 0: yield n n -= 1 print(" finished") gen = countdown(3) # nothing printed yetprint("created")print(next(gen))print(next(gen))for value in gen: # resumes where it paused print(value)
Output
Press Run (⌘ Enter) to see what happens.
The for loop and the generator take turns
for loopcountdown(3)next()yield 3next()yield 2next()StopIteration

The body starts running for the first time.

1/6
Quick check
What does calling countdown(3) do on its own?
Need a nudge? A hint rules out a wrong answer.

Iterator exhaustion bugs

Single use sounds harmless until it bites in production. The classic shape: a function receives "some rows", checks them, then processes them. With a list that works. Someone later swaps the list for a generator to save memory, and the processing step silently sees fewer rows, or none. No exception, no warning, just a wrong number.

Python
def parse(rows): for row in rows: yield int(row) orders = parse(["5", "12", "7"]) if any(n > 10 for n in orders): # "validate" first... print("has a big order") print("total:", sum(orders)) # ...then process
Output
Press Run (⌘ Enter) to see what happens.

any stops as soon as it finds 12, so it has already consumed 5 and 12. sum gets only what is left: 7. The same trap hides in other places:

  • x in gen consumes items up to and including the match. Everything after it is still there, everything before it is gone.
  • Logging or printing a generator for debugging (print(list(rows))) empties it for the real code below.
  • Passing one iterator to two consumers, such as zip(it, it). That one is sometimes a deliberate trick for pairing items, but it confuses readers.
  • A generator stored on an object (self.items = (x for x in ...)) that a second method loops over again. The second loop finds nothing.

The fixes are boring, which is good. If you need more than one pass, materialise once with rows = list(rows) at the top of the function and say so in a comment. If the data is too big for that, restructure into one pass that computes everything at once. itertools.tee can split one iterator into several, but it buffers every item one copy has seen and the other has not, so if one copy runs far ahead, you are back to holding the whole list in memory. In function signatures, type the parameter as Iterable[int] when you loop once and as Sequence[int] when you need len, indexing or two passes. The annotation tells the caller what they may pass.

Predict the outputPython

What does this print?

gen = (n for n in range(10))
print(5 in gen)
print(list(gen))
Need a nudge? Hints walk you through it.

Iterable classes vs iterator classes

When you write your own collection, you choose which of the two roles your class plays, and getting it wrong reproduces the exhaustion bug inside your own type.

An iterator class has __next__ and an __iter__ that returns self. That return self is what makes it single use: every for loop gets the same object, already partly walked. An iterable class has an __iter__ that returns a new iterator every call. The easiest way to do that is to make __iter__ a generator function, so each call creates a fresh generator.

Python
class Countdown: """An iterator: __iter__ returns self, so it is single use.""" def __init__(self, start): self.current = start def __iter__(self): return self def __next__(self): if self.current <= 0: raise StopIteration self.current -= 1 return self.current + 1 class Playlist: """An iterable: every __iter__ call hands out a fresh iterator.""" def __init__(self, songs): self.songs = list(songs) def __iter__(self): for song in self.songs: # a generator: a new one per call yield song c = Countdown(3)print(list(c), list(c)) p = Playlist(["intro", "verse"])print(list(p), list(p))print([(a, b) for a in p for b in p][:3]) # nested loops need two iterators print(iter(c) is c, iter(p) is p)
Output
Press Run (⌘ Enter) to see what happens.

The rule of thumb: containers (things that hold data, like Playlist, a query result you already fetched, a matrix) should be iterables. Iterators are for things that are naturally one pass: a network stream, a database cursor, a file. That is also why open() returns an iterator: the operating system file position really does move forward.

The last line shows a handy check. For any iterator, iter(x) is x is true. For a re-iterable container it is false. Some libraries use exactly that test to refuse a one-shot iterator where they need two passes.

Quick check
A teammate's Report class has __iter__ that returns self and a __next__ that walks self.rows. A nested loop for a in report: for b in report: produces far fewer pairs than expected. What is the cleanest fix?
Need a nudge? A hint rules out a wrong answer.

Lazy evaluation saves memory

A list holds every element in memory at once. A generator holds only its current state, no matter how many values it will produce. That is called lazy evaluation: values are computed only when someone asks.

Python
import sys eager = [n * n for n in range(1_000_000)] # a list comprehensionlazy = (n * n for n in range(1_000_000)) # a generator expression print("list bytes: ", sys.getsizeof(eager))print("generator bytes:", sys.getsizeof(lazy))print(sum(lazy) == sum(eager))
Output
Press Run (⌘ Enter) to see what happens.

The list uses megabytes; the generator uses about two hundred bytes, whatever the range. The syntax difference is only the brackets: [...] builds a list, (...) builds a generator expression. When you pass one straight into a function, you can drop the extra parentheses: sum(n * n for n in nums).

Laziness also lets you work with infinite sequences and build pipelines where each stage pulls one item at a time from the previous one:

Python
def read_lines(): # pretend this is a huge log file yield "INFO start" yield "ERROR disk full" yield "INFO retry" yield "ERROR timeout" errors = (line for line in read_lines() if line.startswith("ERROR"))messages = (line.split(" ", 1)[1] for line in errors)for m in messages: print(m)
Output
Press Run (⌘ Enter) to see what happens.

Nothing runs until the final for pulls. At any moment only one line is in flight through the whole pipeline.

Quick check
When should you use a list instead of a generator?
Need a nudge? A hint rules out a wrong answer.

Generator pipelines for real log processing

The toy pipeline above scales up into one of the most useful patterns in everyday Python work. A support ticket says checkout is slow. You have a few gigabytes of JSON log lines and want to know which paths are failing. Write each step as a small generator function that takes an iterable and yields results, then plug them together.

A pull-based log pipeline
app.log: a file is an iteratorapp.loga file is an iteratorread_lines: strip newlinesread_linesstrip newlinesparse: JSON, skip bad linesparseJSON, skip bad linesonly(ERROR): keep matchesonly(ERROR)keep matchesCounter: pulls every itemCounterpulls every itemlinestrdictdict

Nothing happens when you build the pipeline. Work starts only when the consumer at the end asks for an item.

1/4
Python
import ioimport jsonfrom collections import Counter LOG = io.StringIO("""\{"level": "INFO", "path": "/home", "ms": 41}{"level": "ERROR", "path": "/checkout", "ms": 1200}not json at all{"level": "INFO", "path": "/checkout", "ms": 380}{"level": "ERROR", "path": "/login", "ms": 95}{"level": "ERROR", "path": "/checkout", "ms": 2100}""") def read_lines(f): for line in f: # a file is already a lazy iterator yield line.rstrip("\n") def parse(lines): for n, line in enumerate(lines, start=1): try: yield json.loads(line) except json.JSONDecodeError: print(f" skip line {n}") # in real code: log it and count it def only(level, events): return (e for e in events if e["level"] == level) def slow(events, ms): return (e for e in events if e["ms"] >= ms) events = parse(read_lines(LOG))errors = only("ERROR", events)by_path = Counter(e["path"] for e in errors)print(by_path.most_common()) LOG.seek(0)first_slow = next(slow(parse(read_lines(LOG)), ms=1000), None)print("first slow request:", first_slow)
Output
Press Run (⌘ Enter) to see what happens.

Look at the second query. next(..., None) stops the whole pipeline after the first match, so the bad line 3 is never even read, and the skip message does not print. On a real file that is the difference between reading 2 lines and 20 million. In a real script, io.StringIO becomes open(path, encoding="utf-8"), and for compressed logs gzip.open(path, "rt", encoding="utf-8") returns the same kind of line iterator, so nothing else changes.

Why this design holds up at work:

  • Each stage is testable alone. parse(["{}", "junk"]) is a one-line unit test with a plain list as input.
  • Stages compose. Adding "only the last hour" is one more small function, not an edit to a 60-line loop.
  • Memory stays flat. The pipeline uses roughly the memory of one record plus whatever the final consumer keeps.

The trade-off is debugging: a stack trace from inside a pipeline points at whichever stage was running, and there is no list to inspect halfway. When something looks wrong, pull a few items with list(islice(stage, 5)) on a fresh pipeline. For very hot paths, the per-item function-call overhead of many tiny stages can matter; Profiling and Making Python Fast shows how to measure before you merge stages.

yield from

yield from other yields every value from another iterable, one by one. It is the clean way for one generator to delegate to another, and it shines in recursive generators.

Python
def flatten(items): for item in items: if isinstance(item, list): yield from flatten(item) # delegate to the recursive call else: yield item print(list(flatten([1, [2, [3, 4]], [], 5])))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

def inner():
  yield 1
  yield 2

def outer():
  yield 0
  yield from inner()
  yield 3

print(list(outer()))
Need a nudge? Hints walk you through it.

Generators can return a value

A generator may end with return something. That value is not yielded. Python attaches it to the StopIteration that ends the generator, as StopIteration.value. A for loop or list() catches that StopIteration and throws the value away, which is why you rarely see it. The place it matters is yield from: the expression yield from sub() evaluates to the sub-generator's return value, so a delegating generator can get a summary back from its helper.

Python
def copy_rows(rows): copied = 0 for row in rows: yield row.upper() copied += 1 return copied # becomes StopIteration.value gen = copy_rows(["a", "b"])print(next(gen), next(gen))try: next(gen)except StopIteration as stop: print("returned:", stop.value) def job(): count = yield from copy_rows(["x", "y", "z"]) # yield from hands back the return value yield f"copied {count} rows" print(list(job()))print(list(copy_rows(["q"]))) # a for loop or list() throws the return value away def first_word(words): it = iter(words) yield next(it) # empty input: StopIteration escapes inside a generator try: print(list(first_word([])))except RuntimeError as e: print("RuntimeError:", e)
Output
Press Run (⌘ Enter) to see what happens.

The last part is a real bug pattern with a safety net. Calling next(it) inside a generator on an empty iterator raises StopIteration inside the generator body. In old Python, that silently ended the generator, which could truncate output with no error at all. Since Python 3.7 (PEP 479), a StopIteration that escapes a generator body is turned into RuntimeError: generator raised StopIteration. If you see that message, look for a bare next() inside a generator, and either pass a default, next(it, None), or catch StopIteration and return.

Predict the outputPython

What does this print?

def gen():
  yield 1
  return 99

def outer():
  result = yield from gen()
  yield result

print(list(gen()))
print(list(outer()))
Need a nudge? Hints walk you through it.

send, throw and close

A generator is a paused function, and you can talk to it while it is paused. You need to recognise these methods more than write them: they appear in older coroutine code, in framework internals, and in interview questions about how async grew out of generators.

  • gen.send(value) resumes the generator and makes the paused yield expression evaluate to value. next(gen) is the same as gen.send(None). You must advance a new generator to its first yield before sending a real value, often called priming it.
  • gen.throw(exc) resumes the generator by raising exc at the paused yield. The generator can catch it and carry on, or let it propagate.
  • gen.close() raises GeneratorExit at the paused yield, so finally blocks and with blocks inside the generator run. Python also calls it when an unfinished generator is garbage collected.
Python
def averager(): total = count = 0 average = None while True: value = yield average # receives what send() passes in total += value count += 1 average = total / count avg = averager()next(avg) # "prime" it: run to the first yieldprint(avg.send(10))print(avg.send(20))print(avg.send(60)) def reader(): print(" open") try: while True: yield "line" finally: print(" closed") # runs on close(), or when the generator is garbage collected r = reader()print(next(r))r.close() # raises GeneratorExit at the paused yieldprint(r.gi_suspended, r.gi_frame) def safe_div(): while True: try: x = yield print(" got", x) except ZeroDivisionError: print(" handled an error thrown in") g = safe_div(); next(g)g.send(4)g.throw(ZeroDivisionError)
Output
Press Run (⌘ Enter) to see what happens.

close has a practical consequence. A generator that opens a file inside with open(...) and is abandoned halfway (say, you break out of the loop after the first match) still has the file open until the generator is closed or garbage collected. In CPython, reference counting usually does that immediately, but other implementations, and generators caught in reference cycles, can hold the file much longer. When cleanup timing matters, close it yourself: contextlib.closing(gen) or an explicit gen.close() in a finally.

These methods are also what make @contextmanager work, which you will use in the next lesson but one, Context Managers. The decorator turns your generator into an object whose __enter__ calls next() to run up to the yield, and whose __exit__ either calls next() again (no error) or calls throw() with the exception from the with body, so your try/except/finally around the yield sees it.

A thirty-line contextmanager, built from send and throw

This is a simplified version of what contextlib does. The real one also checks that the generator yields exactly once and gives clearer errors, but the core is exactly this.

Python
class tiny_contextmanager: """A stripped-down contextlib.contextmanager, to show the mechanism.""" def __init__(self, gen_func): self.gen_func = gen_func def __call__(self, *args): self.gen = self.gen_func(*args) return self def __enter__(self): return next(self.gen) # run up to the yield def __exit__(self, exc_type, exc, tb): try: if exc is None: next(self.gen) # resume after the yield else: self.gen.throw(exc) # re-raise inside the generator except StopIteration: return exc is not None # generator finished: suppress the error it handled return False @tiny_contextmanagerdef transaction(name): print(f" BEGIN {name}") try: yield name.upper() print(" COMMIT") except ValueError: print(" ROLLBACK") with transaction("orders") as tx: print(" working in", tx) with transaction("refunds"): raise ValueError("bad amount")print("the error was handled inside the generator")
Output
Press Run (⌘ Enter) to see what happens.

Notice that the ValueError did not escape. The generator caught it and finished, so the context manager reported it as handled. Re-raise inside the except (a bare raise after the rollback) if callers must still see the error. That is usually what you want for a real transaction.

Native async def coroutines started life as generators driven by send, and they still share the same machinery underneath: an event loop resumes a paused coroutine much as send resumes a generator. Async and Await covers the modern syntax; you never need send to write async code today.

Put it in order5 steps

Order what happens when you run avg = averager(); next(avg); avg.send(10).

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

itertools: the iterator toolbox

The itertools module is a set of fast, lazy building blocks. These are the ones worth knowing by heart:

FunctionWhat it yieldsExample
count(start)start, start+1, ... foreverIDs, infinite indexes
islice(it, n)the first n items (slicing for iterators)take from an infinite stream
chain(a, b)everything from a, then from bjoin iterables without copying
groupby(it, key)runs of consecutive items with the same keygroup sorted data
product(a, b)every pair, like nested loopsgrid coordinates
permutations(it, r)every orderingbrute-force small searches
combinations(it, r)every subset of size r, order ignoredpick 2 of n
pairwise(it)(a, b), (b, c), ...differences between neighbours
batched(it, n)tuples of up to n items (3.12+)send rows in chunks
Python
from itertools import count, islice, chain, groupby, product, permutations, combinations, pairwise, batched print(list(islice(count(100), 3)))print(list(chain([1, 2], "ab")))words = ["apple", "avocado", "banana", "blueberry", "cherry"]print({k: list(g) for k, g in groupby(words, key=lambda w: w[0])})print(list(product("ab", [1, 2])))print(len(list(permutations("abc"))), len(list(combinations("abcd", 2))))print([b - a for a, b in pairwise([1, 4, 9, 16])])print(list(batched(range(7), 3)))
Output
Press Run (⌘ Enter) to see what happens.

One trap: groupby only groups consecutive equal keys. Sort by the same key first, or you get the same key several times. The next lesson, functools, itertools and operator, goes through these by job (sliding windows, running totals, cutting streams) and covers the rest of the module.

Match the pairs0/5 matched

Pick the itertools function for each job.

Choose an item, then its match on the other side.
ChallengeMedium

Chunk any iterable

Write a generator chunks(items, n) that yields lists of up to n consecutive items from any iterable. The last chunk may be shorter. If n < 1, raise ValueError.

list(chunks([1, 2, 3, 4, 5], 2))   # [[1, 2], [3, 4], [5]]
list(chunks("abc", 3))             # [["a", "b", "c"]]

It must be lazy: it should work on an infinite iterator like itertools.count() as long as the caller only takes a few chunks. So do not call list(items) or len(items). Write it yourself rather than calling itertools.batched.

Python
from collections.abc import Iterable, Iterator def chunks(items: Iterable, n: int) -> Iterator[list]: # Collect items into a list and yield it each time it reaches n. pass
ChallengeEasy

Flatten with yield from

Write a generator flatten(nested) that yields every non-list value from an arbitrarily nested list, in order, left to right.

list(flatten([1, [2, [3, [4]]], [], 5]))   # [1, 2, 3, 4, 5]
list(flatten(["ab", ["cd"]]))              # ["ab", "cd"]  (strings are values, not lists)

Use recursion and yield from.

Python
from collections.abc import Iterator def flatten(nested: list) -> Iterator: pass
Key terms
iterable
Anything with __iter__, which returns an iterator. Lists, strings, dicts and files are iterables.
iterator
An object with __next__ that produces values one at a time and raises StopIteration at the end.
generator
An iterator created by a function containing yield; it pauses at each yield and keeps its state.
generator expression
(expr for x in it): a lazy, one-pass version of a list comprehension.
yield from
Yields every value from another iterable, delegating to it.
lazy evaluation
Computing values only when they are requested, so memory use stays constant.
exhaustion
An iterator that has produced all its values stays empty; looping again yields nothing, without an error.
StopIteration.value
Where a generator's return value goes; yield from evaluates to it.
send / throw / close
Generator methods that resume it with a value, with an exception, or with GeneratorExit to run its cleanup.