Custom Iterator
Implement a class that can be iterated over using __iter__ and __next__.
IntermediateTopic: Object-Oriented Programs
Python Custom Iterator Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# 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
Understanding Custom Iterator
By defining __iter__ and __next__, Countdown becomes an iterator usable in for-loops.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.