Python 3D Academyবাংলা

Generators: functions that pause with yield

🌍 In real life. A grandmother tells you one chapter of a long story each night. When you ask for more, she doesn't start again from the beginning: she remembers exactly where she stopped, like a bookmark, and carries on from there.

A generator function works like her. It is a normal def with yield inside instead of (or as well as) return:

  • calling it doesn't run the body: it gives back a generator, paused before the first line
  • each next() runs the body until the next yield, hands out that value, and pauses with a bookmark
  • the next next() carries on right after that yield
  • when the function ends, next() raises StopIteration, like any iterator

The idea in one sentence: a function with yield in it is a generator function: calling it gives a paused generator, and each next() runs it to the next yield, hands out that value, and pauses again.

Its words:

  • yield: hand out one value and pause, keeping every local variable
  • generator: the paused function, which is also an iterator
  • lazy: values are made only when asked for
def story():
    print("(opening the book)")
    yield "Chapter 1: the village"
    yield "Chapter 2: the river"
    yield "Chapter 3: the tiger"

book = story()
print("Got the book")
print(next(book))
print(next(book))
for chapter in book:      # a for loop asks for the rest
    print(chapter)
"(opening the book)" only prints at the first next(): making the generator ran nothing.

yield vs return, step by step:

  1. return hands back one answer and the function is finished; its local variables are gone
  2. yield hands back one of many answers and the function only pauses; its local variables stay, ready for the next round
  3. a generator can only be gone through once, like any iterator; call the function again for a fresh one
def countdown(n):
    while n > 0:
        yield n
        n = n - 1
    yield "Lift off!"

print(list(countdown(3)))
print(list(countdown(1)))

Why generators? A function that builds a list of a million items needs memory for all of them before you see the first. A generator hands them out one at a time, so it uses almost no memory, can start answering at once, and can even describe a sequence that never ends.

Mistakes and edge cases.

  • Expecting the body to run at the call. story() runs nothing; only next() (or a loop) does.
  • Asking for its length or an index. len(g) gives TypeError: object of type 'generator' has no len(), and g[0] gives TypeError: 'generator' object is not subscriptable. Use list(g) if you really need them.
  • Looping twice. The second loop finds the generator used up; call the function again for a fresh one.
  • return with a value. A return inside a generator just ends it; the value isn't handed out by next().

Quiz

  1. What does this print?

    def colours():
        yield "red"
        yield "green"
    
    c = colours()
    print(next(c), next(c))
  2. What does this print?

    def numbers():
        print("start")
        yield 1
    
    g = numbers()
    print("made")
    print(next(g))
  3. What happens to a generator's local variables at a yield?

    • They are kept, ready for the next next()
    • They are deleted, like after return
    • They are reset to 0
  4. What does this print?

    def double_up(items):
        for x in items:
            yield x * 2
    
    g = double_up([1, 2, 3])
    print(list(g))
    print(list(g))
  5. Which line has a mistake? (The function should give every number from 1 to n.)

    def one_to(n):
        for i in range(1, n + 1):
            return i
    
    print(list(one_to(3)))

Coding tasks

  1. Write a generator countdown(n) that yields n, n-1, … down to 1.

  2. Write a generator evens_up_to(n) that yields the even numbers from 0 up to and including n.

  3. Write a generator chapters(titles) that yields "Chapter 1: <title>", "Chapter 2: <title>" and so on, one per title.