Hi Pythonistas!
In the previous post we discussed what is iterator? By default, Python provides many iterators (like iterating over lists or strings). But sometimes, we need to create custom iterators for special use cases.
In this post, we will learn how to create an iterator from scratch using Python’s __iter__() and __next__() methods.
Steps to Create a Custom Iterator
To make a class behave like an iterator, it must:
- Implement __iter__() – This should return the iterator object itself.
- Implement __next__() – This should return the next value and raise StopIteration when done.
A Simple Counter Iterator
Let's create an iterator that counts up to a given number.
code
class Counter:
def __init__(self, max_count):
self.max_count = max_count
self.current = 0
def __iter__(self):
return self # An iterator must return itself
def __next__(self):
if self.current >= self.max_count:
raise StopIteration
self.current += 1
return self.current
counter = Counter(3)
for num in counter:
print(num)
Output:
1
2
3
What Happens Here?
The Counter class initializes with a maximum count.
The __iter__() method returns self, making the object an iterator.
The __next__() method returns the next number and stops when max_count is reached.
When Should You Use a Custom Iterator?
- When dealing with large datasets that you don’t want to store in memory.
- When you need customized iteration behavior, like generating specific sequences.
- When working with infinite data streams, such as reading data from a sensor or API.
Hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in