Generators & Iterators
🎓 Advanced · Topic 02
Generators & Iterators
Process massive datasets lazily — one item at a time — without loading everything into memory. Master the iterator protocol and the power of yield.
⏱ ~55 min
🔴 Advanced
💾 Memory efficiency
The Iterator Protocol
Any object that implements __iter__ and __next__ is an iterator. Python's for loop calls these methods under the hood.
Generator Functions with yield
Any function containing yield becomes a generator. It pauses execution at each yield and resumes when the next value is requested.
⚡ vs list — memory comparison
[x**2 for x in range(1_000_000)] allocates ~8 MB. (x**2 for x in range(1_000_000)) allocates ~120 bytes. Same values, 66,000× less memory.
Generator Expressions
Like list comprehensions but with parentheses — lazy by default, perfect for chaining transformations.
yield from — Delegating to Sub-generators
yield from delegates to another iterable, transparently forwarding values and exceptions.