Applying transformations to a collection
In the Writing generator functions with the yield statement recipe, we looked at writing a generator function. The examples we saw combined two elements: a transformation and a source of data. They generally look like this:
for item in source: new_item = some transformation of item yield new_item
This template for writing a generator function isn't a requirement. It's merely a common pattern. There's a transformation process buried inside a for
statement. The for
statement is largely boilerplate code. We can refactor this to make the transformation function explicit and separate from the for
statement.
In the Using stacked generator expressions recipe, we defined a start_datetime()
function which computed a new datetime
object from the string values in two separate columns of the source collection of data.
We could use this function in a generator function's body like this:
def start_gen(tail_gen): ...