Sobes.tech
Junior — Middle

What specific methods need to be implemented to create your own iterator object?

sobes.tech AI

Answer from AI

To create a custom iterator object in Python, you need to implement two special methods:

  1. __iter__(self) — should return the iterator object itself. This allows the object to be used in loops and other constructs expecting an iterator.

  2. __next__(self) — returns the next element in the sequence. When the end of the sequence is reached, it should raise a StopIteration exception.

Here's an example of a simple iterator that returns numbers from 1 to 3:

class MyIterator:
    def __init__(self):
        self.current = 1
        self.max = 3

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= self.max:
            val = self.current
            self.current += 1
            return val
        else:
            raise StopIteration

# Usage
for num in MyIterator():
    print(num)