Implementing Custom Iterators
Hard
+4 pts
🎯 In Python, you make any object iterable by implementing __iter__ and __next__:
class Countdown: def __init__(self, start): self.current = start def __iter__(self): return self def __next__(self): if self.current <= 0: raise StopIteration val = self.current self.current -= 1 return val
Or more commonly, you use a generator:
def countdown(start): while start > 0: yield start start -= 1
Rust uses the same idea — a trait with a next() method — but the payoff …
Login to see the full exercise.
Topics