advancedAdvanced Topics
Generators & Iterators
Create memory-efficient iterables with yield and iterator protocol.
In this lesson
01Generator Functions
Use yield to produce a sequence of values lazily, one at a time.
Python
1def countdown(n):2 while n > 0:3 yield n4 n -= 156for num in countdown(5):7 print(num, end=" ")
Output
5 4 3 2 1
02Iterator Protocol
Implement __iter__ and __next__ to create custom iterable objects.
Python
1class Counter:2 def __init__(self, start, end):3 self.current = start4 self.end = end56 def __iter__(self):7 return self89 def __next__(self):10 if self.current > self.end:11 raise StopIteration12 val = self.current13 self.current += 114 return val1516for n in Counter(1, 5):17 print(n, end=" ")
Output
1 2 3 4 5