The first stateful generator: take()

The first generator we'll look at is take() which retrieves a specified number of elements from the front of a sequence:

def take(count, iterable):
"""Take items from the front of an iterable.

Args:
count: The maximum number of items to retrieve.
iterable: The source of the items.

Yields:
At most 'count' items from 'iterable'.
"""
counter = 0
for item in iterable:
if counter == count:
return
counter += 1
yield item
Note
That the function defines a generator because it contains at least one yield statement. This particular generator also contains a return statement to terminate the stream of yielded values. The generator simply uses a counter to keep track of how many elements have been yielded so far, returning when a request is made for any elements beyond that requested count.

Since generators are lazy, and only produce values on request, we'll drive execution with a for-loop in a run_take() function:

def run_take():
items = [2, 4, 6, 8, 10]
for item in take(3, items):
print(item)

Here we create a source list named items which we pass to our generator function along with a count of 3. Internally, the for-loop will use the iterator protocol to retrieve values from the take() generator until it terminates.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset