Sobes.tech
Junior — Middle

Have you created your own implementations of iterators in your projects?

sobes.tech AI

Answer from AI

Yes, in Python, it is common to create custom iterators, especially when you need to implement specific data traversal logic.

An iterator is an object that implements the __iter__() and __next__() methods.

Here's an example of a custom iterator that iterates numbers from 1 to n:

class CountUpTo:
    def __init__(self, max_value):
        self.max = max_value
        self.current = 0

    def __iter__(self):
        return self

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

# Usage:
for number in CountUpTo(5):
    print(number)

This type of iterator is useful when you need to control the traversal process or create lazy sequences.