Python Generators — Explain Like I'm 5
The Snack Dispenser Idea
Imagine you want 1,000 cookies.
You could:
- bake all 1,000 first, then carry a giant box, or
- use a machine that gives one cookie each time you press a button
A generator is that machine.
Normal lists make everything at once. Generators make one item at a time, only when asked. That saves memory and feels smooth when data is huge.
def countdown(n):
while n > 0:
yield n
n -= 1
for number in countdown(3):
print(number)
Output:
- 3
- 2
- 1
yield is the magic word.
When Python sees yield, it pauses the function and remembers where it stopped. Next time, it continues from that exact spot.
Why this matters
If you read a massive log file, you usually do not want the whole file in memory. You want one line, then the next, then the next.
Generators are perfect for:
- reading big files
- handling streaming data
- making endless sequences (like numbers forever)
One Thing to Remember
A generator creates values on demand with
yield, so your program can process big or endless data without loading everything at once.
See Also
- Python Async Await Async/await helps one Python program juggle many waiting jobs at once, like a chef who keeps multiple pots moving without standing still.
- Python Basics Python is the programming language that reads like plain English — here's why millions of beginners (and experts) choose it first.
- Python Booleans Make Booleans click with one clear analogy you can reuse whenever Python feels confusing.
- Python Break Continue Make Break Continue click with one clear analogy you can reuse whenever Python feels confusing.
- Python Closures See how Python functions can remember private information, even after the outer function has already finished.