Concept
Generators: The `yield` Keyword
`yield` pauses the function and emits a single value, resuming only when the caller asks for the next item. This uses near-zero RAM.
python
def count_to_three():
yield 1
yield 2
yield 3
gen = count_to_three()
print(next(gen)) # 1
print(next(gen)) # 2
# 106. Generators: The `yield` Keyword `yield` pauses the function and emits a single value, resuming only when the caller asks for the next item. This uses near-zero RAM: ```python def count_to_three(): yield 1 yield 2 yield 3 gen = count_to_three() print(next(gen)) # 1 print(next(gen)) # 2 ``` Generating a 10,000,000-item list consumes hundreds of megabytes of memory. A generator yields one item at a time on demand, consuming almost zero RAM regardless of dataset size.
Checkpoint
What happens to a generator function's state when it hits `yield`?
Practice
Write a generator function `countdown(n)` that yields numbers down from `n` to `1` using `while n > 0: yield n; n -= 1`. Loop over `countdown(3)` and print each number.
01
Tap code blocks below to assemble
Available Blocks