A generator is a Python iterator that produces a sequence lazily. A function containing yield pauses at each yielded value and resumes when iteration advances, avoiding storage of the entire sequence in memory. section 5.7.1
Generators support several closely related iteration patterns:
- Calling a generator function creates a generator object without immediately running its loop. section 5.7.1
- Calling next advances execution to the next yield; a for loop can advance through all yielded values. section 5.7.1
- Asynchronous generators combine yield with await and are consumed using async for, making delayed values available incrementally. section 5.7.1
- Older asyncio code used generator-based coroutines with yield from before async and await syntax. section 14.5.1
Lazy integer production
Define positive_integers(until) with a loop that yields each integer. Calling positive_integers(2) creates a generator; successive next calls produce 0 and 1 without first building a list. section 5.7.1
Listing 5.13 A synchronous generator
def positive_integers(until: int):
for integer in range(until):
yield integer
positive_iterator = positive_integers(2)
print(next(positive_iterator))
print(next(positive_iterator))
Inspect the synchronous generator listing showing yield, generator creation, and explicit next calls. section 5.7.1











