8.1 Iterators & Generators (yield & Lazy O(1) Memory)
Process gigabytes of data in 200 bytes of RAM! Understand how Python's for-loop protocol works under the hood, write lazy generator functions with yield, and compare list vs. generator memory.
1. The Netflix Streaming Analogy (Eager List vs. Lazy Generator)
Imagine watching a 20 GB 4K movie:
- A
listis like downloading the entire 20 GB file into RAM before you can watch frame 1. - A Generator (
yield) is like streaming — it computes and hands you one frame at a time, using almost zero RAM!
2. Iterable vs. Iterator Under the Hood
Every Python for x in items: loop secretly calls two built-in functions:
it = iter(items)→ asks the Iterable (like a list or string) for an Iterator (a bookmark tracking your current position).next(it)→ pulls the next item one by one untilStopIterationsignals the end.
3. Writing Generators with yield
A function containing yield instead of return becomes a Generator Function. Every time Python hits yield, it pauses the function, remembers all local variables, hands back the value, and waits until the next next() call!
def countdown(n):
while n > 0:
yield n # Pauses here and hands back n!
n -= 1
for num in countdown(3):
print(num) # 3, 2, 1
# Generator Expression — just replace [...] with (...)!
total = sum(n * n for n in range(1_000_000)) # Uses O(1) constant RAM!
Real-World Superpower: Streaming Huge Log Files
def error_lines(filepath):
with open(filepath, "r", encoding="utf-8") as f:
for line in f:
if "ERROR" in line:
yield line.strip() # Streams 50 GB logs without loading into RAM!
Watch Out: Generators are single-use! Once exhausted, looping over the same generator a second time yields nothing — create a fresh generator if you need a second pass.
4. Interactive Trace: Watching yield Pause & Resume State
Quick Quiz: Module 8.1 — Iterators & Generators
Keep Exploring: Related Lessons & Tools
All Courses →Compare two versions of text, source code, config files, or JSON payloads side-by-side using exact LCS diffing with recursive JSON key sorting and patch export.
Convert Unix epoch seconds/milliseconds to ISO-8601 and local timezones, and bulk-generate UUID v4, time-ordered UUID v7, and sortable ULIDs.