ZetCode

Python __next__ Method

Last modified November 18, 2026 Python 3.15

An iterator implements __next__ to produce the next value and raises StopIteration when exhausted. Together with __iter__, which returns the iterator itself, this forms the iterator protocol used by for loops and many built-ins. This article covers the basic pattern, defaults for next(), infinite sequences, in-memory line iteration, chaining, resettable iterators and iterables that can be traversed repeatedly.

The iterator protocol

A class becomes an iterator by defining __next__ for values and __iter__ returning self. The example counts from zero up to, but not including, a limit.

count_up_to.py
class CountUpTo:
    def __init__(self, stop):
        self.stop = stop
        self.current = 0

    def __iter__(self):
        return self

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


counter = CountUpTo(4)
print(next(counter), next(counter))
print(list(counter))

The two explicit next() calls consumed 0 and 1; the list() call collected the rest. An iterator is stateful — once consumed it does not restart on its own.

$ python count_up_to.py
0 1
[2, 3]

StopIteration and default values

When the sequence is exhausted, __next__ raises StopIteration. The two-argument form next(it, default) returns the default instead of raising.

stop_iteration.py
class Once:
    def __init__(self, value):
        self.value = value
        self.done = False

    def __iter__(self):
        return self

    def __next__(self):
        if self.done:
            raise StopIteration
        self.done = True
        return self.value


it = Once("only")
print(next(it))
print(next(it, "default"))
try:
    next(it)
except StopIteration:
    print("exhausted")

The first call returned the value, the second returned the supplied default, and the third raised StopIteration which the try/except caught. A for loop uses the same exception internally to know when to stop.

$ python stop_iteration.py
only
default
exhausted

An infinite iterator

An iterator need not terminate. This Fibonacci generator never raises StopIteration, so the caller decides how many values to take with itertools.islice.

fibonacci.py
import itertools


class Fibonacci:
    def __init__(self):
        self.a, self.b = 0, 1

    def __iter__(self):
        return self

    def __next__(self):
        result = self.a
        self.a, self.b = self.b, self.a + self.b
        return result


fib = Fibonacci()
print(list(itertools.islice(fib, 10)))

The state lives in the instance and is updated on every call. Because the sequence is unbounded, list(fib) would never finish; slicing it is the safe way to inspect a prefix.

$ python fibonacci.py
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Iterating over lines in memory

A line iterator can wrap any source of text. Here io.StringIO plays the role of a file so the example stays self-contained while still demonstrating one-line-at-a-time processing.

line_iterator.py
import io


class LineIterator:
    def __init__(self, text):
        self.lines = iter(io.StringIO(text))

    def __iter__(self):
        return self

    def __next__(self):
        line = next(self.lines)
        return line.rstrip("\n")


text = "first line\nsecond line\nthird line\n"
for line in LineIterator(text):
    print(line.upper())

Each call to __next__ asks the underlying StringIO iterator for one line; when it raises StopIteration, the line iterator propagates it and the loop ends. No whole-file buffering is needed.

$ python line_iterator.py
FIRST LINE
SECOND LINE
THIRD LINE

Chaining iterators

A chain presents several iterables as one continuous stream. When the current sub-iterator is exhausted, __next__ advances to the next one; when the last is exhausted, the StopIteration from next(self.iterables) ends the chain.

chain.py
class Chain:
    def __init__(self, *iterables):
        self.iterables = iter(iterables)
        self.current = iter(next(self.iterables))

    def __iter__(self):
        return self

    def __next__(self):
        try:
            return next(self.current)
        except StopIteration:
            self.current = iter(next(self.iterables))
            return next(self.current)


chained = Chain([1, 2], "ab", (3.5,))
print(list(chained))

A list, a string and a tuple were joined into one sequence. The hook works with any iterable, since it only calls iter() and next(). The standard library offers the equivalent itertools.chain.

$ python chain.py
[1, 2, 'a', 'b', 3.5]

A resettable iterator

Iterator state can be managed explicitly. A reset() method returns the cursor to the start so the same object can be traversed again.

resettable.py
class ResettableRange:
    def __init__(self, start, stop):
        self.start = start
        self.stop = stop
        self.reset()

    def reset(self):
        self.current = self.start

    def __iter__(self):
        return self

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


ranger = ResettableRange(2, 5)
print(list(ranger))
ranger.reset()
print(list(ranger))

Both traversals produced the same values because reset() reinitialized the cursor. Without that call, the second list(ranger) would have been empty.

$ python resettable.py
[2, 3, 4]
[2, 3, 4]

Iterable versus iterator

An iterable returns a fresh iterator from __iter__, so it can be traversed repeatedly. An iterator returns self and is consumed once. The two classes below show the difference.

iterable_vs_iterator.py
class NumberIterator:
    def __init__(self, start, stop):
        self.current, self.stop = start, stop

    def __iter__(self):
        return self

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


class NumberIterable:
    def __init__(self, start, stop):
        self.start, self.stop = start, stop

    def __iter__(self):
        return NumberIterator(self.start, self.stop)


iterator = NumberIterator(1, 3)
iterable = NumberIterable(1, 3)
print(list(iterator), list(iterator))
print(list(iterable), list(iterable))
print(iter(iterable) is iter(iterable))

The iterator yielded its values only once. The iterable produced a new iterator on each iter() call, so both traversals worked and the two iterator objects were distinct.

$ python iterable_vs_iterator.py
[1, 2] []
[1, 2] [1, 2]
False

Best practices

A few rules keep iterators well behaved:

Source

Iterator types - Python documentation

object.__next__ - Python documentation

next() - Python documentation

itertools - Python documentation

In this article we have implemented the __next__ method. We have covered the iterator protocol, StopIteration, default values, infinite sequences, in-memory line iteration, chaining, resettable iterators and reusable iterables. For related topics, see Python __iter__ method, Python generators, and Python itertools.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.