0Pricing
Python Academy · Lesson

Generator Functions

Produce values lazily with yield.

Generator Functions is a free Python Academy lesson on CoddyKit — lesson 2 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.

What Is a Generator?

A generator function looks like a normal function but uses yield instead of (or alongside) return. Calling it does not run the body; it returns a generator object, which is an iterator.

def gen():
    yield 1
    yield 2
    yield 3

g = gen()
print(type(g).__name__)
print(list(g))

yield Pauses Execution

Each time you call next(), the function runs until it hits a yield, returns that value, and freezes its state. The next call resumes right after the yield.

def steps():
    print('start')
    yield 'a'
    print('resumed')
    yield 'b'

g = steps()
print(next(g))
print(next(g))

Looping Over a Generator

Because a generator is an iterator, a for loop drives it automatically and stops when the function ends (which raises StopIteration internally).

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for x in countdown(4):
    print(x)

Lazy Evaluation

Generators are lazy: values are produced only when requested. This means you can model very large or infinite sequences without using lots of memory.

def naturals():
    n = 1
    while True:
        yield n
        n += 1

g = naturals()
print(next(g), next(g), next(g))

State Between Yields

Local variables keep their values between yield points. A generator naturally remembers where it left off, with no manual index bookkeeping.

def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

g = fib()
print([next(g) for _ in range(7)])

Generators vs Building a List

A regular function builds and returns the whole list at once. A generator yields items on demand. Use a generator when the sequence is large or you might stop early.

def squares_list(n):
    result = []
    for i in range(n):
        result.append(i * i)
    return result

def squares_gen(n):
    for i in range(n):
        yield i * i

print(squares_list(5))
print(list(squares_gen(5)))

Stopping Early

Because production is lazy, you can break out of a loop and the generator simply never computes the rest.

def naturals():
    n = 1
    while True:
        print('producing', n)
        yield n
        n += 1

for x in naturals():
    if x > 3:
        break
    print('got', x)

return Inside a Generator

A bare return in a generator simply ends it (raising StopIteration). Any value you return becomes the exception's value attribute, which most loops ignore.

def up_to(stop):
    i = 0
    while True:
        if i >= stop:
            return
        yield i
        i += 1

print(list(up_to(4)))

Generators Are Single-Use

Like all iterators, a generator is consumed once. After exhaustion it yields nothing. Call the function again to get a fresh generator.

def gen():
    yield 1
    yield 2

g = gen()
print(list(g))
print(list(g))
print(list(gen()))

Filtering With Generators

Generators make clean data pipelines. Here we yield only the even numbers, one at a time.

def evens(numbers):
    for n in numbers:
        if n % 2 == 0:
            yield n

print(list(evens(range(10))))

Chaining Generators

A generator can consume another generator, building a multi-stage pipeline where each stage is lazy.

def numbers(n):
    for i in range(n):
        yield i

def doubled(src):
    for x in src:
        yield x * 2

print(list(doubled(numbers(5))))

Quick Check

Test your understanding of generator functions.

Recap

You learned generator functions:

  • yield pauses and resumes execution, preserving local state.
  • Calling the function returns a lazy generator object.
  • They are memory friendly and great for pipelines and infinite streams.
  • They are single-use, like any iterator.

Next: the even more compact generator expressions.

Frequently asked questions

Is the “Generator Functions” lesson free?

Yes — the full text of “Generator Functions” 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 “Generator Functions”?

Produce values lazily with yield. 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 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Generator Functions” 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. The Iterator Protocol
  2. Generator Functions
  3. Generator Expressions
  4. yield from and Delegation
← Back to Python Academy