Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Python · Module

__next__

__next__() is the iterator protocol method that returns the next item. It must raise StopIteration when the iterator is exhausted.

How it works

Define __next__ without arguments to produce the next value from an iterator. Once no values remain, it must raise StopIteration; iteration constructs use that exception to detect completion.

Syntax

object.__next__()

Returns

The next element of the iterator; raises StopIteration when no elements remain.

Key points

  • Call next(iterator) as the usual built-in interface for invoking __next__().
  • An iterator exposes values incrementally rather than producing the complete sequence at once.
  • A class implementing both methods can return itself from __iter__().

Example: Implementing an iterator

class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current == 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

for value in Countdown(3):
    print(value)

This iterator returns successive values and signals completion by raising StopIteration.

When to use it

Custom iterators

Create a custom object consumed by for loops.

Streaming data

Generate values incrementally without materializing a collection.

Stateful iteration

Control stateful traversal through a sequence or resource.

  • __iter__
  • next()
  • StopIteration
  • iter()

Source: 9. Classes — Python 3.15.0 documentation. Checked 2026-10-15.