Generator pipelines allow us to use multiple generators to perform a series of operations all within one expression. We can break down complex operations into smaller, more manageable parts where they can then be pipelined together to achieve the desired output.
To pipeline generators, the input to one generator function can be the output of another generator function. That resulting generator can then be used as input for another generator function, and so on.
Pipeline generators are also often referred to as nested generators. We can use a pipelined generator like in the following example:
my_generator = combined_generator(first_generator(second_generator))
Where the output of
second_generator is the input for
first_generator which in total becomes the input for
Let’s practice more with generator pipelines!
We have three courses:
- Computer Science which has 5 students
- Art which has 10 students
- Business which has 15 students
First, complete the generator function called
course_generator that can yield tuples of (Course name, Number students) for the above courses and the corresponding number of students. The first tuple for Computer Science has been provided.
We need to add 5 students to each course. Create a generator function called
add_five_students that takes in an input variable called
courses object contains tuples of (Course name, Number of students). The
add_five_students generator function should loop through the
courses input object.
On each iteration, it should yield a tuple containing the course name and number of students plus 5. The resulting generator that is yielded should have the following values:
- Computer Science with 10 students
- Art with 15 students
- Business with 20 students.
Use a pipeline generator (nested generator) to get the resulting generator that has the 5 added students to each course. Set it to a variable called
Print out each course tuple in the resulting
increased_courses generator using a