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 next yield, hands out that value and pauses, keeping all local variables.
  • When the function reaches its end (or a return), the generator raises StopIteration for you.

Compare that to the 15-line Doubling class from earlier!

Pip tip: A function becomes a generator just by containing yield anywhere in its body. You never write raise StopIteration in a generator; just return or let the function end.

Assignment

Write a generator function fuel_drain(fuel, burn) that tracks a lantern burning through its fuel:

  1. While fuel is above 0, yield the current fuel, then subtract burn.
  2. list(fuel_drain(10, 3)) is [10, 7, 4, 1].
  3. fuel_drain(0, 5) yields nothing.