0Pricing
Python Academy · Lesson

The yield Keyword

Write generator functions with yield for custom iterators.

The yield Keyword is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Introduction

Generator functions use yield to produce a sequence of values lazily, pausing execution between each yield.

What is yield?

A function with yield is a generator function. Each call to next() resumes from the last yield.
def count_up(n):
    for i in range(n):
        yield i
for x in count_up(3):
    print(x)

Generator Function vs Regular Function

Calling a generator function returns a generator object — it does NOT run any code yet. The code runs as you iterate.
def gen():
    print('start')
    yield 1
    print('middle')
    yield 2
g = gen()  # no print yet
print(next(g))  # 'start', then 1

Infinite Generator

def naturals(n=0): while True: yield n; n+=1 is an infinite sequence. Use with islice or break.
def naturals(n=0):
    while True:
        yield n
        n += 1
import itertools
print(list(itertools.islice(naturals(), 5)))

yield from

yield from sub_gen() delegates to a sub-generator, forwarding all values. Equivalent to for x in sub: yield x.
def chain(*iters):
    for it in iters:
        yield from it
print(list(chain([1,2], [3,4], [5])))

Sending Values with send()

gen.send(value) resumes the generator AND passes a value that becomes the result of the yield expression.
def accumulator():
    total = 0
    while True:
        n = yield total
        if n is None: break
        total += n
g = accumulator()
next(g)  # prime
print(g.send(10))
print(g.send(5))

Generator State

A generator pauses at each yield and retains its local variables between calls — a natural coroutine.
def stateful():
    seen = set()
    while True:
        item = yield
        seen.add(item)
        yield len(seen)
g = stateful()
next(g); g.send('a'); print(next(g)); g.send('b'); print(next(g))

Closing a Generator

gen.close() throws GeneratorExit inside the generator. Use a try/finally inside the generator for cleanup.
def resource_gen():
    try:
        while True:
            yield
    finally:
        print('cleaned up')
g = resource_gen()
next(g)
g.close()

StopIteration and Return

return value in a generator sets the value attribute of the StopIteration exception. Used by yield from to retrieve it.
def gen_with_return():
    yield 1
    yield 2
    return 'done'
g = gen_with_return()
try:
    while True: print(next(g))
except StopIteration as e:
    print('returned:', e.value)

Fibonacci Generator

Generators excel at infinite mathematical sequences: yield a; a, b = b, a+b
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b
import itertools
print(list(itertools.islice(fibonacci(), 10)))

Generators vs Classes with __iter__

Generators are simpler than writing a class with __iter__ and __next__. Use generators for straightforward sequences.
# Generator is simpler than:
# class Counter:
#     def __iter__(self): return self
#     def __next__(self): ...
print('generators simplify iterators')

Quick Check

What does yield from sub() do in a generator function?

Recap

yield pauses a generator function. Generator functions return a generator object. yield from delegates to sub-generators. send() passes values in. close() triggers cleanup.

Keep Going

Excellent! Continue to the next lesson to deepen your skills.

Frequently asked questions

Is the “The yield Keyword” lesson free?

Yes — the full text of “The yield Keyword” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “The yield Keyword”?

Write generator functions with yield for custom iterators. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “The yield Keyword” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. List Comprehensions
  2. Set and Dict Comprehensions
  3. Generator Expressions
  4. The yield Keyword
← Back to Python Academy