Custom Iterator in Python
Implement a class that can be iterated over using __iter__ and __next__.
IntermediateObject-Oriented ProgramsExample 12 of 25
custom-iterator.py
Run in browser1# Program to implement a custom iterator23class Countdown:4 def __init__(self, start):5 self.current = start67 def __iter__(self):8 return self910 def __next__(self):11 if self.current <= 0:12 raise StopIteration13 value = self.current14 self.current -= 115 return value1617for num in Countdown(3):18 print(num)
Output
3 2 1
What's going on
By defining __iter__ and __next__, Countdown becomes an iterator usable in for-loops.