__next__Easy Examples

Returns the next value from an iterator; raises StopIteration when done

Implementing __next__

Basic implementation of __next__ in a class.

python
class Counter:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0

    def __iter__(self):
        return self

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

for n in Counter(3):
    print(n)

__next__ returns the next value from an iterator; raises stopiteration when done. Implementing it lets you customize how Python interacts with your objects.

__next__ in action

Seeing __next__ called by Python's built-in operations.

python
# How Python calls __next__ automatically
class Demo:
    def __init__(self, value):
        self.value = value

    def __next__(self):
        print(f"__next__ was called!")
        return self

d = Demo(42)
# This triggers __next__:
print(d)

Python automatically calls __next__ when you use the corresponding operator or function on your object.

Want to try these examples interactively?

Open Easy Playground