Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Classes and Special Methods

__iter__() and __next__()

Reference for Python __iter__() and __next__(): write your own iterators and iterables, raise StopIteration, reuse and generator-based __iter__.

__iter__() makes an object iterable: it returns an iterator, the thing a for loop will actually step through. __next__() makes an object an iterator: each call returns the next item and, when there are none left, raises StopIteration.

Two designs are common. A class can be its own iterator (__iter__() returns self, and __next__() keeps state), which is one-shot. Or a class can be a reusable iterable, whose __iter__() returns a fresh iterator each time, often by being a generator function.

Python
class Countdown:
    def __init__(self, start):
        self.n = start
    def __iter__(self):
        return self
    def __next__(self):
        if self.n <= 0:
            raise StopIteration
        self.n -= 1
        return self.n + 1

Try it

Python A one-shot iterator class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python A reusable iterable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
class Iterable:
    def __iter__(self):
        return iterator

class Iterator:
    def __iter__(self):
        return self
    def __next__(self):
        ...  # return the next item or raise StopIteration
Method Description
__iter__(self) Called by iter(obj) and by for. Must return an iterator.
__next__(self) Called by next(it). Returns the next item.

Return value: __iter__() returns an object with __next__(); __next__() returns the next item.

Raises: StopIteration from __next__() to signal the end. iter() raises TypeError ("object is not iterable") if __iter__() is missing and there is no __getitem__() fallback; it also raises TypeError if __iter__() returns something that is not an iterator.

Usage notes

  • Iterators must be iterable too. Return self from __iter__() so an iterator works directly in a for loop or list().
  • Self-iterators are single use. Running list(c) twice gives the second empty list. If users need repeated loops, make __iter__() return a new iterator or be a generator function.
  • Generator __iter__ is the simplest correct design: it creates fresh state on each loop and needs no __next__() or StopIteration.
  • Keep state off the iterable when several loops may run at once (nested loops over the same object); store position in the iterator.
  • Everything that consumes iterables works: unpacking, list(), sum(), sorted(), in, zip(), dict(), str.join().
  • Once exhausted, stay exhausted. After StopIteration, further __next__() calls should keep raising it.
  • Don't modify the underlying collection while iterating it; a list iterator skips items, a dict iterator raises RuntimeError.
  • Infinite iterators are fine; just limit consumption with itertools.islice or break.
  • Async version: __aiter__() and __anext__() (raising StopAsyncIteration) for async for.