Python Generator Pipeline: Take First N Items (islice)
A Python generator pipeline chains generators, so each item passes through every stage before the next item is read. itertools.islice() takes the first N items and stops the whole pipeline early.
You will chain two stages, stop a stage with a counter, and take items with islice(). Prerequisites: Python Generator Function: Filter Lines with yield.
Chain two generators into a pipeline
Pass one generator to another. Each stage does one job.
def evens(numbers): for number in numbers: if number % 2 == 0: yield numberdef squared(numbers): for number in numbers: yield number * numberfor value in squared(evens(range(1, 9))): print(value)This prints 4, 16, 36, 64. evens() filters and squared() changes each value. Neither builds a list.
Each item flows through one at a time
The print() lines below show the order of the work.
def evens(numbers): for number in numbers: if number % 2 == 0: print("evens passes on", number) yield numberdef squared(numbers): for number in numbers: print("squared receives", number) yield number * numberfor value in squared(evens([1, 2, 3, 4])): print("loop gets", value)The lines for 2 all print before any line for 4. The last stage asks, and the request travels back down the chain.
Stop a stage early with a counter and break
A stage can end before its source does. Keep a running value, and break when it reaches a limit.
def until_total(numbers, limit): total = 0 for number in numbers: yield number total += number if total >= limit: breakprint(list(until_total([4, 3, 5, 9, 2], 10)))This prints [4, 3, 5]. The check comes after the yield. A check at the top of the loop would run only after the loop had already asked for 9.
Take the first N items with islice()
islice(source, n) from the itertools module yields the first n items of any iterable, then stops.
from itertools import islicedef counting(): number = 1 while True: yield number number += 1for value in islice(counting(), 3): print(value)This prints 1, 2, 3. counting() is infinite, but islice() asks it for only three values.
A generator cannot be sliced with square brackets
def counting(): number = 1 while True: yield number number += 1print(counting()[:3]) # this line raises TypeError: a generator is not subscriptableA list slice needs every item to exist already. Use islice() for anything lazy. If the source has fewer than n items, islice() yields what there is.
Note: The print() lines inside the stages are only there to show the order of the work; remove them in real code. The inputs are tiny so the output stays short.
See also: Infinite Generators in Python: Running State, Python Iterators.
Your turn
counting() is supplied. Write the filter multiples_of_seven(numbers), then print the first three values of the pipeline with islice().
7 14 21
from itertools import islicedef counting(): number = 1 while True: yield number number += 1# Define multiples_of_seven(numbers), then loop over islice(..., 3) and print each value.