Content · Programming · Python

Python __iter__() and __next__(): Iterable Classes

Make custom objects iterable with __iter__() and __next__().

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Make custom objects iterable with __iter__() and __next__().

How It Works


__iter__() returns an iterator and __next__() yields one item at a time until raising StopIteration. A container may return a new iterator so separate loops do not interfere with each other.

Iterator objects are typically consumed; containers can create fresh iterators in __iter__().

Step-by-Step Example


class Countdown:
    def __init__(self, starting_number):
        self.current_number = starting_number

    def __iter__(self):
        return self

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

print(list(Countdown(3)))

Understanding the Example


  • The class groups related state and methods so each instance can manage its own values.
  • The function definition gives the operation a reusable name and makes its inputs explicit.

A successful run of this example prints the following output:

[3, 2, 1]

Where This Fits in a Real Program


A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.

Practice: Try It Yourself


Change the iterator to count upward from zero to a configured limit.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Returning a list from __iter__() instead of an iterator object.
  • Forgetting to raise StopIteration when the sequence is exhausted.

Key Takeaways


  • Make custom objects iterable with __iter__() and __next__().
  • __iter__() returns an iterator and __next__() yields one item at a time until raising StopIteration.
  • Iterator objects are typically consumed; containers can create fresh iterators in __iter__().
Share this resourceSend this page to someone who may find it useful.