Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

`object.__next__`: advancing an iterator

`__next__` returns one item and advances the iterator. Once the iterator is exhausted, the method raises `StopIteration` on every further call.

Version: Python 3.12

Syntax

class MyIterator:
    def __iter__(self): ...
    def __next__(self): ...

# Built-in calls
iter(iterable)
next(iterator)
next(iterator, default)

In Python 3.12, object.__next__ here denotes a special method on an iterator object, not a method of the built-in object class. Define __next__(self) on the iterator class. A successful call returns one item and updates the iterator’s state so the following call resumes at the next position.

An iterable designed for repeatable traversal can create a fresh iterator each time its __iter__ runs. In the example, Letters.__iter__ does this, and LetterIterator.__init__ gives each iterator its own starting position. By contrast, LetterIterator.__iter__ returns self, so iter(a) neither makes a copy nor resets the position.

When no items remain, __next__ must raise StopIteration, and it must keep raising it on later calls. Do not return None to signal exhaustion: None is a valid item. The built-in next(a) calls __next__ and propagates the exception, while next(a, default) returns the supplied default on exhaustion. A for loop obtains an iterator and ends when it encounters StopIteration.

Examples

class Letters:
    def __iter__(self):
        return LetterIterator()


class LetterIterator:
    def __init__(self):
        self.position = 0

    def __iter__(self):
        return self

    def __next__(self):
        letters = ('A', 'B')
        if self.position >= len(letters):
            raise StopIteration
        letter = letters[self.position]
        self.position += 1
        return letter


letters = Letters()
a = iter(letters)
b = iter(letters)
print(next(a))
print(iter(a) is a)
print(next(a))
print(next(b))
print(next(a, 'END'))
try:
    next(a)
except StopIteration:
    print('StopIteration')

Result

A
True
B
A
END
StopIteration

After the first `A`, `iter(a) is a` is `True`, and `a` then returns `B`. The independent iterator `b` starts at `A`. Once `a` is exhausted, the call with a default gives `END`, and the call without a default raises `StopIteration`.

Related lessons

  • Python · Lesson 8 · Advanced · Version: 5

Sources