Summary - Generators
- Python course
- Intermediate
- Lesson 105/116
- 5 min
Combine yield, yield from and send to write a log stream.
Summary - Generators
In this group we covered defining generators with yield, the generator object and the next() call, publishing inner generators with yield from, sending values and errors with send and throw, and terminating with close.
Generators work lazily and do not hold all data in memory. yield produces and pauses; next advances; yield from wires an inner generator; send sends a value; close terminates. Now we'll write an example that combines these.
Practice Combined summary example
Define the function def gen():. In the body include yield 1, yield from [2, 3] and yield 4. Then print all values with print(list(gen())).
Starter code
# Write a generator with yield and yield fromSample solution
# Write a generator with yield and yield from
def gen():
yield 1
yield from [2, 3]
yield 4
print(list(gen()))Expected output
[1, 2, 3, 4]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which construct publishes an inner generator?
- yield
- yield from Correct answer
- send
- close
Explanation: yield from publishes all values from an inner generator.
2 Match the generator concepts
| Term | Meaning |
|---|---|
yield |
Produce value |
next |
Advance |
yield from |
Inner generator |
close |
Terminate |
3 yield from line
def gen():
yield 1
____ [2, 3]
yield 4
def gen():
yield 1
yield from [2, 3]
yield 4
Explanation: yield from [2, 3] publishes the list.
4 Match the summary example parts
| Term | Meaning |
|---|---|
def gen |
Generator definition |
yield 1 |
Single value |
yield from [2, 3] |
List publish |
print(list(gen())) |
List result |