Generator pipeline

MediumIterator & Generator Programs · 10 of 20

Write a pipeline of generators that reads numbers, keeps the even ones and squares them.

Advertisement
Output
[4, 16, 36, 64, 100]

Approach

  1. Each generator consumes the previous one.

Solution

Python
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.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Leave a Comment