Python Practice › Iterator & Generator Programs › Program 10
Generator pipeline
Write a pipeline of generators that reads numbers, keeps the even ones and squares them.
Output
[4, 16, 36, 64, 100]
Approach
- Each generator consumes the previous one.
Solution
def numbers(limit): yield from range(1, limit + 1) def only_even(source): for n in source: if n % 2 == 0: yield n def squared(source): for n in source: yield n * n print(list(squared(only_even(numbers(10)))))Output
[4, 16, 36, 64, 100]
Line by line
Line 2
yield from hands out every value of another iterable.
Line 13
Only one value at a time moves through the pipeline.
Learn the concept
New to this topic? Read the lesson, then come back.