Generator
Generator
🎯 By the end of this lesson
After reading this lesson, you will be able to confidently do the following 3 things.
- ▸✅ The mechanism by which
yieldturns a function into a generator - ▸✅ Memory efficiency (generator instead of a large list)
- ▸✅ Using
itertools(chain, islice, groupby)
Keep these learning goals as a checklist, and close the lesson once you can answer all of them.
5 Core Generator Concepts — Code + Output
generator = a function that lazily produces values one at a time. Saves memory + enables infinite sequences.
1. list vs generator — Memory Difference
[ ] → list, ( ) → generator. A single character difference, but the memory usage differs by a factor of hundreds of billions.
2. yield — Creating a Generator
When yield is hit, the function yields a value and pauses. On the next call, it resumes from that exact line.
3. next() — Pulling Values One at a Time
⚠️ An infinite sequence is impossible with a list — this is the generator's unique strength.
4. Real-World Pattern — Reading a Large File Line by Line
5. return vs yield Difference
One-Line Summary
Key point: Large data, infinite sequences, streaming → generator. Small data → list.
🐍 Try It Out — Generator
🤖 Try Asking AI Like This
Knowing the concepts from this lesson lets you give AI specific instructions. Instead of a vague "fix this," you make vocabulary-driven requests — that is the starting point for saving tokens.
- ▸"Convert this large list build to a generator (yield) to save memory"
- ▸"Use itertools to make this more efficient"
Why This Reduces Tokens
Without understanding the concept, even after receiving an AI response you have to ask "What is that?" again. That follow-up question is what burns tokens. Learn the concept once, and the conversation ends in a single exchange.