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
- The Iterator Protocol
- Generator Functions
- Generator Expressions
- yield from and Delegation