Build Lazy Processing Pipelines
Core idea
A lazy pipeline connects iterators: each stage requests items from the previous stage when needed. A filter may pull several inputs to produce one accepted output. Generator expressions and generator functions avoid building full intermediate lists if their stages retain only limited state. The original source and final consumer may still hold data in memory.
readings = [2, -1, 4, 0]valid = (x for x in readings if x >= 0)scaled = (x * 10 for x in valid)print(sum(scaled))sum consumes the pipeline without a list of scaled values.
Observe demand
def source(): for x in [1, 2, 3]: print("read", x) yield xeven = (x for x in source() if x % 2 == 0)print("ready")print(next(even))even.close()The filter consumes two inputs to provide one result; the third input is not requested.
Bound a consumer
def take(items, limit): it = iter(items) for _ in range(limit): try: value = next(it) except StopIteration: return yield valuesource = iter([8, 9, 10])print(list(take(source, 2)))print(next(source))The limit prevents reading an extra item. Early exhaustion also stops the generator.
Common mistake
Lazy does not mean every algorithm uses constant memory: sorted and list materialize their input, and some stages buffer data. A consumed pipeline cannot be restarted without rebuilding it from a suitable source.
Practice
Build a generator pipeline that filters positive readings, doubles them, and takes at most three accepted items. Instrument the source and verify how many inputs it reads for empty and short inputs.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Lazy pipelines
Check your understanding of lazy pipelines.
What is printed?
valid = (x for x in [-2, 1, 3] if x > 0)print(sum(x * 2 for x in valid))What is printed?
def source(): for x in [1, 2, 3]: print("read", x) yield xg = (x for x in source() if x % 2 == 0)print(next(g))g.close()What is printed?
g = (x for x in [1, 2])print(sum(g), sum(g))Which operation necessarily materializes all remaining items of a finite generator into a list?