Python
# Program to implement a custom iterator
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
for num in Countdown(3):
print(num)Output
3 2 1
By defining iter and next, Countdown becomes an iterator usable in for-loops.