advancedAdvanced Topics

Generators & Iterators

Create memory-efficient iterables with yield and iterator protocol.

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 n
4 n -= 1
5
6for 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 = start
4 self.end = end
5
6 def __iter__(self):
7 return self
8
9 def __next__(self):
10 if self.current > self.end:
11 raise StopIteration
12 val = self.current
13 self.current += 1
14 return val
15
16for n in Counter(1, 5):
17 print(n, end=" ")
Output
1 2 3 4 5