Iterators & Generators
Iterables and iterators
- An iterable is anything you can loop over (list, string, dict, file).
- An iterator produces values one at a time:
iter()creates one,next()gets the next value, andStopIterationsignals the end.
A for loop does exactly this behind the scenes.
Generators: the easy way to make iterators
A function with yield instead of return. Each yield hands back one value and pauses the function until the next value is requested.
Why they matter
- Memory: values are made on demand, so you can process a 10 GB log file line by line or even an infinite sequence.
- Pipelines: chain generators together like an assembly line.
Things to know
- A generator can be used only once; after that it's exhausted.
yield from other()passes along every value from another generator.itertoolshas ready-made tools:count,islice,chain,cycle,groupby.
▶️ Runs in the app.
Example
from itertools import islice
def fibonacci():
a, b = 0, 1
while True: # infinite, but values come one at a time
yield a
a, b = b, a + b
print(list(islice(fibonacci(), 10))) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
def countdown(n):
while n > 0:
yield n
n -= 1
gen = countdown(3)
print(next(gen), next(gen), next(gen)) # 3 2 1
print(list(gen)) # [] — already used up
# A tiny pipeline
lines = ["ok", "ERROR disk full", "ok", "ERROR timeout"]
errors = (line for line in lines if line.startswith("ERROR"))
messages = (line.split(" ", 1)[1] for line in errors)
print(list(messages)) # ['disk full', 'timeout']