Content · Programming · Python

Python Make a Custom Class Work with for Loops

Make a collection-like class iterable by returning an iterator from __iter__.

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

Make a collection-like class iterable by returning an iterator from __iter__.

What You Will Learn


A for loop asks iter(object) for an iterator and repeatedly calls next() until StopIteration. For a simple container, __iter__ can delegate to iter(self._items) instead of storing iteration state on the container itself. That way, separate loops can iterate independently.

Class interfaces should preserve their stated invariants. Type annotations describe intent but do not enforce runtime types on their own.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

class ReadingList:
    def __init__(self, books):
        self._books = list(books)

    def __iter__(self):
        return iter(self._books)

titles = ReadingList(["Python Basics", "Algorithms"])
for title in titles:
    print(title)
print(list(titles))

How the Example Works


  • The class ReadingList groups data and behavior; its methods run when called on an instance.
  • The variable titles holds the result of ReadingList(['Python Basics', 'Algorithms']). Later lines use that value or inspect how it changes.
  • The loop demonstrates when each value is processed or when cleanup and exception handling take effect.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

Expected output from the example:

Python Basics
Algorithms
['Python Basics', 'Algorithms']

When You Would Use This


A class becomes useful when several operations must maintain rules around related data. Think about which state belongs to each instance, which operations should be public, and how errors should be reported. Avoid making the design more complex than the underlying task.

Practice: Modify the Code


Add __len__ and explain why it does not replace __iter__.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Returning a plain list from __iter__ rather than an iterator object.
  • Keeping one shared cursor on a reusable container so two nested loops interfere.

Key Takeaways


  • Make a collection-like class iterable by returning an iterator from __iter__.
  • A for loop asks iter(object) for an iterator and repeatedly calls next() until StopIteration.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.