Applying transformations to a collection
Once we've defined a generator function, we'll need to apply the function to a collection of data items. There are a number of ways that generators can be used with collections.
In the Writing generator functions with the yield statement recipe earlier in this chapter, we created a generator function to transform data from a string into a more complex object. Generator functions have a common structure, and generally look like this:
def new_item_iter(source: Iterable) -> Iterator:
for item in source:
new_item = some transformation of item
yield new_item
The function's type hints emphasize that it consumes items from the source collection. Because a generator function is a kind of Iterator
, it will produce items for another consumer. This template for writing a generator function exposes a common design pattern.
Mathematically, we can summarize this as follows:
The...