An iterator is an object in Python that can be iterated (looped) upon. They implement two methods: __iter__()
and __next__()
.
You can create an iterator by defining a class that implements these two methods:
class MyIterator:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current > self.end:
raise StopIteration
self.current += 1
return self.current - 1
iter_obj = MyIterator(1, 5)
for num in iter_obj:
print(num)
In the above code, MyIterator
is a custom iterator that loops from start
to end
.
Create an iterator class that generates a sequence of even numbers between a given range.
StopIteration
exception?Answers: An iterator must implement __iter__()
and __next__()
. StopIteration
is raised to indicate that there are no more items to return from the iterator.