Python Fundamentals · Objects, Errors and Generators

Generators and yield

A generator hands out values one at a time and pauses in between. Watch it freeze at each yield and pick up exactly where it left off.

generators.py

def countdown(n):
    while n > 0:
        yield n           # hand back one value, then pause right here
        n = n - 1

ticks = countdown(3)      # nothing runs yet: this only makes the generator
first = next(ticks)       # runs until the first yield
rest = []
for t in ticks:           # carries on from where it paused
    rest.append(t)
print(first, rest)

Step by step

  1. Python defines the function countdown(). Its body does not run yet: it runs each time the function is called.
  2. Calling countdown(3) does not run its body. It just creates a paused generator object.
  3. next() runs the generator until the first yield…
  4. Python checks n > 0 to decide whether the loop keeps going.
  5. …which hands back 3 and freezes the generator right here, keeping n = 3.
  6. next() runs the generator until the first yield…
  7. The value it returned, [], is stored in rest.
  8. The for loop asks the generator for its next value, which wakes it up where it paused.
  9. The for loop asks for the next value: the generator resumes after the yield, with n still 3.
  10. Python checks n > 0 to decide whether the loop keeps going.
  11. Line runs: yield n # hand back one value, then pause right here.
  12. The for loop asks the generator for its next value, which wakes it up where it paused.
  13. 2 is added to the end of the list that rest points to.
  14. The for loop asks the generator for its next value, which wakes it up where it paused.
  15. n changes from 2 to 1.
  16. n = 1: still > 0.
  17. Line runs: yield n # hand back one value, then pause right here.
  18. The for loop asks the generator for its next value, which wakes it up where it paused.
  19. 1 is added to the end of the list that rest points to.
  20. The for loop asks the generator for its next value, which wakes it up where it paused.
  21. n changes from 1 to 0.
  22. n = 0: the while ends, the generator finishes, and the for loop stops.
  23. The for loop asks the generator for its next value, which wakes it up where it paused.
  24. first = 3 and rest = [2, 1]. The generator produced each value only when asked, pausing in between.