
Code
Your First yield
Writing __iter__ and __next__ by hand is a lot of typing. A generator
function does the same job with one magic keyword: yield.
def doubling(limit):
value = 1
while value <= limit:
yield value
value *= 2
print(list(doubling(20))) # [1, 2, 4, 8, 16]
How it works
- Calling
doubling(20)runs none of the body. It returns a generator object, which is an iterator. - Each
next()runs the body until the nextyield, hands out that value and pauses, keeping all local variables. - When the function reaches its end (or a
return), the generator raisesStopIterationfor you.
Compare that to the 15-line Doubling class from earlier!
Pip tip: A function becomes a generator just by containing
yieldanywhere in its body. You never writeraise StopIterationin a generator; justreturnor let the function end.
Assignment
Write a generator function fuel_drain(fuel, burn) that tracks a lantern
burning through its fuel:
- While
fuelis above 0,yieldthe currentfuel, then subtractburn. list(fuel_drain(10, 3))is[10, 7, 4, 1].fuel_drain(0, 5)yields nothing.
Write a generator function fuel_drain(fuel, burn) that tracks a lantern
burning through its fuel:
- While
fuelis above 0,yieldthe currentfuel, then subtractburn. list(fuel_drain(10, 3))is[10, 7, 4, 1].fuel_drain(0, 5)yields nothing.
main.py Python sleeping
Press Run to try your code, then Check to test it.