28/34
Part 8 of 8 · Follow-upsLearn and do
A chain of generators moves each item through every step before it reads the next
Some inputs are too big to hold at all, like a log that keeps growing. Generators handle those one item at a time.
from collections import Counter
def read(n):
for i in range(n):
yield f" Sensor-{i % 7} reading {i} OK \n" if i % 5 else "\n"
stripped = (line.strip() for line in read(20_000))
kept = (line for line in stripped if line)
lowered = (line.lower() for line in kept)
counts = Counter(line.split()[0] for line in lowered)
A generator produces one item at a time, when it's asked: a function with yield, or a comprehension in parentheses. Building the chain does no work. No line is read until Counter asks for the first item, and then that line goes through every stage before the next one is read.
The same 20,000-line pipeline, once with a list at each stage and once with a chain of generators. The lists peaked at 3,844 KB. About how much did the generators take?
Pick an answer above to see the rest