python · level 3 · unit 1 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A hands out values one at a time with .
Put yield in a function and it becomes a generator. Calling it runs nothing yet: it gives you an iterator. Each next() runs the code up to the next yield, hands out that value, then pauses right there.
Generators are , so they only work when asked. One can read a huge log line by line, or count forever, without ever holding everything in memory.
A is a comprehension in round brackets. sum(n * n for n in range(4)) adds up the squares without building a list first.
def countdown(start):
while start > 0:
yield start
start = start - 1
yield "Lift off!"
for step in countdown(3):
print(step)
print(sum(n * n for n in range(4))) When a generator's code reaches the end, it raises StopIteration for you.
guess first
Watch when each line runs. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
def lines():
print("opening")
yield "first"
print("reading on")
yield "second"
reader = lines()
print("ready")
print(next(reader))
your turn
Your turn. Stream only the error lines.
Fill the blank with the word that hands one value out of a generator. Add an ERROR line of your own to the log if you like.
fix it
You want every even number, but this crashes.
- The function stops at the very first even number. Which word ends a function for good?
returnhands back one value and finishes. You want to hand out many and keep going.- Change
returntoyieldon line 4, then run.
nailed it
you made values on demand. :D
yieldhands out a value and pauses the function.- Generators are lazy: no work happens until you ask.
sum(x for x in items)skips building a whole list.
new words in your collection
- generator
- yield
- lazy
- generator expression
This lesson isn’t saved. A free account remembers every lesson you finish.