Skip to content
Python

Iterator

Custom iterator implementation.

By EZ4Code Team
iteratoriterator

Code

class Range:
    def __init__(self, start, end, step=1):
        self.current = start
        self.end = end
        self.step = step

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.end:
            raise StopIteration
        value = self.current
        self.current += self.step
        return value

for i in Range(1, 10, 2):
    print(i)

# Using iter() and next()
it = iter([1, 2, 3])
print(next(it), next(it))

Explanation

Implement __iter__ and __next__ methods to make an object iterable.

More Python Snippets