Sometimes, we want to build a basic Python iterator.
In this article, we’ll look at how to build a basic Python iterator.
How to build a basic Python iterator?
To build a basic Python iterator, we can define a class with the __iter__ and __next__ methods.
For instance, we write:
class Counter:
def __init__(self, low, high):
self.current = low - 1
self.high = high
def __iter__(self):
return self
def __next__(self):
self.current += 1
if self.current < self.high:
return self.current
raise StopIteration
for c in Counter(3, 9):
print(c)
We define the Counter iterator class.
The __iter__ method which returns self.
And the __next__ method returns the the next value to return with the iterator.
We increment self.current by 1 and return that if self.current is less than self.high.
Otherwise, we raise the StopIteration error to stop the iterator.
Finally, we use the iterator with the for loop to print the value between 3 and 9 exclusive.
Therefore, we see:
3
4
5
6
7
8
printed.
Conclusion
To build a basic Python iterator, we can define a class with the __iter__ and __next__ methods.