Generators and yield
A function that pauses instead of returning, producing one value at a time and holding almost nothing in memory.
Overview
yield instead of return
def countdown(n):
while n > 0:
yield n
n -= 1
return ends a function. yield suspends it, keeping every local variable exactly as it was, and the function continues from that line when the next value is requested.
Calling countdown(3) runs none of the body. It returns a generator object; the code inside starts running only when something asks for a value — next(), a for loop, list(), sum().
generators.py
generator_memory.py
Worth knowing
yield pauses the function and hands a value back; the next request resumes it.(x for x in y) is a generator expression - a comprehension with round brackets.