Generator layer
- Python course
- Intermediate
- Lesson 114/116
- 6 min
Set up data flow with generators and itertools.
Generator layer: produce with yield
In this lesson you will write the uret generator function. This function produces words one by one with yield:
def uret(words):
for w in words:
yield w
for w in uret(words):
print(w)The starting code includes the previous solutions. You will add the uret function and the for loop. A generator produces values one by one without loading the whole list into memory.
This saves memory with large data.
Practice Write and consume the uret generator
Define def uret(words): with for w in words: yield w in the body. Then write for w in uret(words): print(w).
Starter code
# Word processing - word list
words = ["elma", "armut", "elma"]
print(len(words))
def say(words):
return len(set(words))
print(say(words))
# write and consume the uret generatorSample solution
words = ["elma", "armut", "elma"]
print(len(words))
def say(words):
return len(set(words))
print(say(words))
def uret(words):
for w in words:
yield w
for w in uret(words):
print(w)Expected output
3 2 elma armut elma
Next step: file I/O
The generator layer is ready — you can produce words one by one. In the next lesson you will add a file I/O layer: reading from a file-like object with with. This layer will show the safe way to read data from files.
The with statement opens the resource and auto-closes it at block end; this prevents resource leaks. It is the foundation of real file operations.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does yield do?
- Breaks the loop
- Raises an error
- Returns a value and pauses Correct answer
- Deletes a variable
Explanation: yield produces a value and pauses; it resumes on the next call.
2 Match the generator
| Term | Meaning |
|---|---|
def uret |
Generator function |
yield |
Produces a value |
for w in uret |
Consumption |
words |
Source data |
3 Complete the yield keyword
def uret(words):
for w in words:
____
def uret(words):
for w in words:
yield w
Explanation: yield w produces the value w and pauses.