Iterators and generators
An iterator hands out values one at a time with next() until it raises StopIteration; every for loop uses one behind the scenes. A generator is the easy way to write your own iterator: a function that uses yield instead of return. Generators are lazy, so they can process huge files or endless streams with almost no memory.
What a for loop really does
colours = ["red", "green"]
it = iter(colours)
print(next(it))
print(next(it))
try:
next(it)
except StopIteration:
print("No more items")red green No more items
A list is iterable: iter() can make an iterator from it. for colour in colours calls iter() once, then next() until StopIteration. Strings, dicts, files and ranges all work the same way.
Generator functions
def countdown(start: int):
print("Starting")
while start > 0:
yield start
start -= 1
print("Lift-off!")
for n in countdown(3):
print(n)Starting 3 2 1 Lift-off!
- Calling
countdown(3)runs nothing yet — it returns a generator object. - Each
next()runs the function until the nextyield, then pauses there. - When the function ends, the generator raises
StopIterationfor you.
Lazy means memory-friendly
import sys
squares_list = [n * n for n in range(1_000_000)]
squares_gen = (n * n for n in range(1_000_000))
print(sys.getsizeof(squares_list) > 1_000_000)
print(sys.getsizeof(squares_gen) < 1_000)
print(sum(squares_gen))True True 333332833333500000
Pipelines of generators
log_lines = [
"INFO start",
"ERROR disk full",
"INFO retry",
"ERROR timeout",
]
def errors(lines):
for line in lines:
if line.startswith("ERROR"):
yield line
def messages(lines):
for line in lines:
yield line.split(" ", 1)[1]
for msg in messages(errors(log_lines)):
print(msg)disk full timeout
Each stage handles one line at a time, so this works the same for 4 lines or a 40 GB log file read with open().
Infinite generators and itertools
import itertools
def ids(prefix: str):
n = 1
while True:
yield f"{prefix}-{n:03}"
n += 1
print(list(itertools.islice(ids("ORD"), 3)))
for size, colour in itertools.product(["S", "M"], ["red", "blue"]):
print(size, colour)
print(list(itertools.batched(range(7), 3)))['ORD-001', 'ORD-002', 'ORD-003'] S red S blue M red M blue [(0, 1, 2), (3, 4, 5), (6,)]
islice takes the first few values from any iterator, product builds every combination, and batched (Python 3.12+) splits data into chunks — handy for sending records to an API in groups.
Practice
Write a generator evens(limit) that yields the even numbers from 0 up to and including limit. Print list(evens(10)), then the sum of evens(100).
[0, 2, 4, 6, 8, 10] 2550