🧭Generator (Programming)
Also known as Generator Function, yield, Generators
A function that pauses at each yield and hands out one value at a time.
Think of it like
It is like a cook who makes one pancake each time you ask. No big stack waits on the side.
Example
Emma needs a million ticket numbers. A generator makes each one only when asked. So they never all sit in memory at once.
Why it matters
It saves memory, because values are made only when needed. It can even describe a list with no end.
Definition
Example code
python
def count_to(n):
i = 1
while i <= n:
yield i
i += 1
print(list(count_to(3)))
# [1, 2, 3]Common mistake
Key takeaways
- 1yield. Hands out a value and pauses.
- 2Lazy. Makes each value only when asked.
- 3An easy iterator. Less code than writing one by hand.