ZetCode

Python __iter__ Method

Last modified November 18, 2026 Python 3.15

Python calls __iter__ whenever it needs an iterator — in a for loop, in a comprehension, or via iter(). The method must return an iterator, which is an object with a __next__ method. This article explains the protocol, the importance of returning a fresh iterator, and two concise ways to build one.

Making an object iterable

The simplest __iter__ delegates to an existing iterable. The for loop calls the hook once, saves the returned iterator, and then asks it for values.

basic_iter.py
class MyIterable:
    def __init__(self, data):
        self.data = data

    def __iter__(self):
        print("__iter__ called")
        return iter(self.data)


items = MyIterable([1, 2, 3])
for item in items:
    print(item)

The hook runs once, not once per element. It returns the iterator of the internal list, and the loop consumes that iterator. Any object with a working __iter__ can be used in the same way.

$ python basic_iter.py
__iter__ called
1
2
3

Return a fresh iterator each time

An iterable must be able to start a new traversal. Returning the same object with stored state breaks the second loop, which is exactly what the old version of this article did. Delegating to a fresh iterator fixes it.

fresh_iterators.py
class CountDown:
    def __init__(self, start):
        self.start = start

    def __iter__(self):
        return iter(range(self.start, -1, -1))


cd = CountDown(3)
print(list(cd))
print(list(cd))
print(iter(cd) is iter(cd))

Both traversals produce all four values, and two calls to iter() give distinct objects. A version that stored a current attribute on the iterable and returned self would yield the values only once; the second list(cd) would be empty.

$ python fresh_iterators.py
[3, 2, 1, 0]
[3, 2, 1, 0]
False

A separate iterator class

For full control, split the responsibilities: the iterable creates a new iterator object, and that object implements __iter__ and __next__. Raising StopIteration ends the loop.

iterator_class.py
class CountDown:
    def __init__(self, start):
        self.start = start

    def __iter__(self):
        return CountDownIterator(self.start)


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

    def __iter__(self):
        return self

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


cd = CountDown(2)
print(list(cd), list(cd))
it = iter(cd)
print(next(it), next(it), next(it))

The iterator is its own __iter__ result, which is the usual pattern for an iterator class. Each list(cd) starts with a fresh counter. Calling next() directly shows that values are produced one at a time; a fourth call would raise StopIteration.

$ python iterator_class.py
[2, 1, 0] [2, 1, 0]
2 1 0

A generator as __iter__

A function containing yield returns a generator, which is already an iterator. Using one inside __iter__ avoids writing a separate class and still gives a fresh iterator on every call.

generator_iter.py
class Squares:
    def __init__(self, limit):
        self.limit = limit

    def __iter__(self):
        for i in range(1, self.limit + 1):
            yield i * i


s = Squares(4)
print(list(s))
print(list(s))

Each call to __iter__ creates a new generator object, so the squares can be produced again. The generator handles __next__ and StopIteration automatically.

$ python generator_iter.py
[1, 4, 9, 16]
[1, 4, 9, 16]

Iterating over a tree

Recursive data structures are a good fit for generator-based iteration. The yield from statement delegates to the child nodes, giving an in-order traversal without any manual stack.

tree_iter.py
class TreeNode:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

    def __iter__(self):
        if self.left:
            yield from self.left
        yield self.value
        if self.right:
            yield from self.right


tree = TreeNode(4,
                TreeNode(2, TreeNode(1), TreeNode(3)),
                TreeNode(6, TreeNode(5), TreeNode(7)))
print(list(tree))

The values arrive in sorted order because the traversal visits the left subtree, then the node itself, then the right subtree. Callers see a simple sequence of values and do not need to know how the tree is structured.

$ python tree_iter.py
[1, 2, 3, 4, 5, 6, 7]

Lazy and infinite sequences

An iterator can compute values on demand, so it does not need a finite backing collection. An infinite sequence is safe as long as the consumer limits how many items it takes.

lazy_fibonacci.py
import itertools


class Fibonacci:
    def __iter__(self):
        a, b = 0, 1
        while True:
            yield a
            a, b = b, a + b


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

islice takes exactly ten values from the endless stream. Only those ten numbers are ever computed; storing the whole sequence would be impossible. This is the main advantage of lazy iteration.

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

__iter__ must return an iterator

Returning a plain list is not enough. Python validates the result of __iter__ and reports the type it actually got, which makes a broken implementation easy to diagnose.

bad_iter.py
class Bad:
    def __iter__(self):
        return [1, 2, 3]


try:
    list(Bad())
except TypeError as e:
    print(type(e).__name__, e)

A list is iterable but is not itself an iterator: it has no __next__. The fix is to return iter([1, 2, 3]) or to make __iter__ a generator function.

$ python bad_iter.py
TypeError Bad.__iter__() must return an iterator, not list

Best practices

A few rules keep iteration predictable:

Source

object.__iter__ - Python documentation

Iterator types - Python documentation

iter() - Python documentation

Generators - Python HOWTO

In this article we have implemented the __iter__ method. We have covered the iteration protocol, fresh iterators, iterator classes, generators, tree traversal, lazy sequences, and the iterator requirement. For related topics, see Python __next__ method, Python generators, and Python iter() function.

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.