Junior — Middle
What steps are needed to implement your own data collection iteration mechanism?
sobes.tech AI
Answer from AI
To implement a custom iteration mechanism over a collection in Python, you need to define an iterator object that implements the __iter__() and __next__() methods.
Main steps:
- Create a collection class that implements the
__iter__()method, returning an iterator. - Create an iterator class that maintains the current position state and implements the
__next__()method, returning the next element or raisingStopIterationat the end.
Example:
class MyCollection:
def __init__(self, data):
self.data = data
def __iter__(self):
return MyIterator(self.data)
class MyIterator:
def __init__(self, data):
self.data = data
self.index = 0
def __next__(self):
if self.index < len(self.data):
result = self.data[self.index]
self.index += 1
return result
else:
raise StopIteration
# Usage
col = MyCollection([1, 2, 3])
for item in col:
print(item)
This way, you create a custom iterator that can be used in for loops and other iterator-based constructs.