0Pricing
Python Academy · Lesson

Generator Functions

Produce values lazily with yield.

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))

All lessons in this course

  1. The Iterator Protocol
  2. Generator Functions
  3. Generator Expressions
  4. yield from and Delegation
← Back to Python Academy