TAB 1 · CODE TRANSFORM
Transform an Iterator into a Generator
Step through the transformation from explicit iterator state to a resumable generator using yield. Resource values below are a teaching visualization normalized to this example—not measured Python memory benchmarks.
Iterator
class PowTwo:
def __init__(self, max):
self.max = max
self.n = 0
def __iter__(self):
return self
def __next__(self):
if self.n <= self.max:
value = 2 ** self.n
self.n += 1
return value
raise StopIteration→
Generator
def pow_two(max):
n = 0
while n <= max:
yield 2 ** n
n += 11. Remove class state
2. Remove __next__
3. Add yield
4. Resume automatically
Performance Comparison
Run the same workload with an explicit Iterator and a Generator. Percentages are normalized against the slower measured runtime in this browser/Python Runtime session.
Iterator—
Waiting for test
Generator—
Waiting for test
Same task
Both implementations generate and consume the same number of values. Increase the input to 100, 1,000 or 10,000 and compare.
Both implementations generate and consume the same number of values. Increase the input to 100, 1,000 or 10,000 and compare.
PYTHON CONSOLE
Ready.
Process Flow
💻 Generated Python
PYTHON CONSOLE
Waiting for a complete flow.
💻 Generator Challenge
PYTHON CONSOLE
Target: order:680ms payment:920ms