Iterators and generators
Overview
You’ve looped over lists, strings, ranges, dictionaries and files. How does one for statement work with all of them — including a 10 GB log file that would never fit in memory? The answer is the iterator protocol, and once you understand it you can write your own lazy sequences with generators.
Iterables and iterators
- An iterable is anything you can loop over: lists, tuples, strings, dicts, sets, files,
range… - An iterator is an object that produces the items one at a time and remembers where it is.
iter() gets an iterator from an iterable; next() asks it for the next item:
colours = ["red", "green", "blue"]
it = iter(colours)
next(it) # 'red'
next(it) # 'green'
next(it) # 'blue'
next(it) # StopIterationWhen there’s nothing left, the iterator raises StopIteration. That’s exactly what a for loop does behind the scenes:
# for colour in colours: print(colour) is roughly:
it = iter(colours)
while True:
try:
colour = next(it)
except StopIteration:
break
print(colour)Iterators are one-way and one-time: once used up, they stay empty. Many built-ins return iterators — zip, map, enumerate, reversed, a file object — which is why printing them shows <zip object at 0x…>, and why list(...) is needed to see the items.
Generator functions: yield
Writing an iterator class by hand is possible but tedious. A generator function is much simpler: a normal function that uses yield instead of (or as well as) return.
def countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(3):
print(x) # 3, 2, 1How it works:
- Calling
countdown(3)doesn’t run the body. It returns a generator object (an iterator). - Each
next()runs the body until the nextyield, hands out that value, and pauses — keeping all its local variables. - The next
next()resumes right after theyield. - When the function ends, the generator raises
StopIteration, and theforloop stops.
Compare it with building a list:
def countdown_list(n):
result = []
while n > 0:
result.append(n)
n -= 1
return resultSame output, but the list version builds every item in memory first. The generator produces each one only when asked.
Why generators matter
Huge data with tiny memory
def read_lines(path):
with open(path, encoding="utf-8") as f:
for line in f:
yield line.rstrip("\n")This processes a file of any size using memory for just one line at a time.
Infinite sequences
A generator can go on forever — the caller decides how much to take:
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
from itertools import islice
list(islice(fibonacci(), 10)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]A list version would never finish.
Stopping early is free
any(), next() and break stop asking for items as soon as they have an answer, so a generator does only the work that’s needed:
first_big = next(n for n in fibonacci() if n > 1000) # 1597Generator pipelines
Generators that take an iterable and yield transformed items can be chained, like Unix pipes. Each item flows through the whole pipeline before the next is read:
def errors(lines):
for line in lines:
if "ERROR" in line:
yield line
def messages(lines):
for line in lines:
yield line.split(" ", 3)[3]
for msg in messages(errors(read_lines("app.log"))):
print(msg)Each stage is small, testable and reusable — and the whole pipeline uses constant memory.
Generator expressions
You met these in Comprehensions: round brackets make a lazy generator instead of a list.
squares = (n * n for n in range(1_000_000)) # nothing computed yet
total = sum(squares) # computed one at a timeUse a generator expression for simple one-line transformations, a generator function when you need statements, state, or several yields.
yield from
A generator can hand over to another iterable with yield from:
def all_lines(paths):
for path in paths:
yield from read_lines(path)Gotchas
- One use only: after looping over a generator, it’s exhausted. Looping again gives nothing, silently. If you need the items twice, make a list — or call the generator function again.
- No
len()or indexing: generators don’t know how many items they’ll produce. Convert withlist()if you need those (and the data fits in memory). - Errors happen late: since the body runs only when iterated, a bug inside shows up during the loop, not when you call the function.
Useful itertools for iterators
from itertools import islice, chain, count, takewhile, pairwise
list(islice(count(10, 5), 3)) # [10, 15, 20] — count() is infinite
list(chain("ab", [1, 2])) # ['a', 'b', 1, 2]
list(takewhile(lambda n: n < 10, fibonacci())) # [0, 1, 1, 2, 3, 5, 8]
list(pairwise([1, 4, 9])) # [(1, 4), (4, 9)]The big idea: a generator is a function that pauses. Use one whenever you’d build a big list only to loop over it once.
A log-processing pipeline
Your program first writes a small log file (in the starter). Then build a pipeline of generators: (1) read_lines(path) yields each line without its newline; (2) errors(lines) yields only lines containing ERROR; (3) messages(lines) yields the text after the third space-separated field (the message). Print every error message. Then (4) write an infinite generator fibonacci() and print the first 10 numbers using itertools.islice; and (5) show how next() works by calling it three times on countdown(3) and catching the StopIteration from a fourth call.
from itertools import islice
with open("app.log", "w", encoding="utf-8") as f:
f.write(
"2026-12-04 10:00:01 INFO Server started\n"
"2026-12-04 10:00:05 ERROR Database timeout\n"
"2026-12-04 10:01:17 INFO User asha logged in\n"
"2026-12-04 10:02:42 ERROR Payment declined for order 1042\n"
)
# 1–3. Generator pipeline
# 4. Fibonacci
# 5. next() and StopIteration
def countdown(n):
while n > 0:
yield n
n -= 1from itertools import islice
with open("app.log", "w", encoding="utf-8") as f:
f.write(
"2026-12-04 10:00:01 INFO Server started\n"
"2026-12-04 10:00:05 ERROR Database timeout\n"
"2026-12-04 10:01:17 INFO User asha logged in\n"
"2026-12-04 10:02:42 ERROR Payment declined for order 1042\n"
)
# 1–3. Generator pipeline
def read_lines(path):
with open(path, encoding="utf-8") as f:
for line in f:
yield line.rstrip("\n")
def errors(lines):
for line in lines:
if "ERROR" in line:
yield line
def messages(lines):
for line in lines:
yield line.split(" ", 3)[3]
for message in messages(errors(read_lines("app.log"))):
print(message)
# 4. Fibonacci
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
print(list(islice(fibonacci(), 10))) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
# 5. next() and StopIteration
def countdown(n):
while n > 0:
yield n
n -= 1
counter = countdown(3)
print(next(counter), next(counter), next(counter)) # 3 2 1
try:
next(counter)
except StopIteration:
print("Finished")Summary
- An iterable (list, string, file, dict…) can give an iterator with
iter(); an iterator hands out items one at a time withnext(). - A
forloop callsiter()once, thennext()repeatedly until StopIteration. - A function containing
yieldis a generator: calling it returns an iterator that runs the body lazily, pausing at each yield. - Generators use almost no memory, so they handle huge files and infinite sequences; but they can only be looped over once.
- Chain generators into pipelines, and use itertools (islice, chain, …) to slice and combine them.