🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Custom Python Collections and the Iterator Protocol

Python CollectionsđŸŸĸ Free Lesson

Custom Python Collections and the Iterator Protocol

Python's for loop does not know anything about lists. It asks two questions of whatever object you hand it: give me an iterator, and then repeatedly give me the next value until you raise StopIteration. Every container in the language is built on that contract, which means a small custom class with three methods can be used anywhere a list would be used, including in comprehensions, unpacking, and zip.

The same is true in the other direction. A class that only implements __iter__ and __next__ is already a full citizen: it can be chained with itertools, consumed by sum, and passed to code that has never heard of your type. Understanding exactly which methods the interpreter looks for, and in what order, removes most of the guesswork from designing a collection.

What You'll Learn

  • 1Explain what the for loop asks of an object and where each answer comes from
  • 2Separate a container from its iterator so a collection can be traversed more than once
  • 3Use collections.abc base classes to inherit protocol behavior instead of reimplementing it
  • 4Pick the standard library container that already solves the problem before writing your own

What the for loop actually calls

When a for statement begins, it calls iter() on the target. That call looks for __iter__ first; if the object lacks it but defines __getitem__, Python falls back to indexed access starting at zero, which is why old-style sequence objects still iterate. Whatever iter() returns must provide __next__, and the loop ends the moment __next__ raises StopIteration.

The distinction between a container and an iterator is the single most important design decision. A container describes what is in the collection and produces a fresh iterator each time it is traversed. An iterator carries the cursor and is consumed exactly once. Reusing an exhausted iterator silently yields nothing on the second pass, which is one of the most common custom-collection bugs.

python
class Range:
    def __init__(self, start, stop=None, step=1):
        if stop is None:
            start, stop = 0, start
        if step == 0:
            raise ValueError("step must not be zero")
        self.start = start
        self.stop = stop
        self.step = step

    def __iter__(self):
        return RangeIterator(self.start, self.stop, self.step)

    def __len__(self):
        span = self.stop - self.start
        return max(0, -(-span // self.step))

    def __contains__(self, value):
        if (value - self.start) % self.step:
            return False
        return self.start <= value < self.stop if self.step > 0 else self.stop < value <= self.start


class RangeIterator:
    def __init__(self, start, stop, step):
        self.current = start
        self.stop = stop
        self.step = step

    def __iter__(self):
        return self

    def __next__(self):
        if self.step > 0 and self.current >= self.stop:
            raise StopIteration
        if self.step < 0 and self.current <= self.stop:
            raise StopIteration
        value = self.current
        self.current += self.step
        return value


numbers = Range(10)
print(list(numbers))   # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(numbers))   # the same, because __iter__ returns a new cursor
print(len(numbers), 7 in numbers)

Notice that __iter__ returns a new RangeIterator each time, while RangeIterator.__iter__ returns self, because an iterator is already its own cursor. Implementing __len__ also unlocks reversed(), in on sequences, and truthful boolean checks, all for a handful of lines.

A priority queue that breaks ties predictably

The standard library's heapq gives logarithmic push and pop but compares entire tuples, so two items with equal priority fall back to comparing the payload itself and can raise a TypeError the moment the payload is not orderable. Inserting a monotonically increasing sequence number as a middle element solves it: equal priorities are resolved by insertion order, which is also what makes the queue stable.

python
import heapq


class PriorityQueue:
    def __init__(self):
        self._heap = []
        self._count = 0

    def push(self, item, priority=0):
        heapq.heappush(self._heap, (-priority, self._count, item))
        self._count += 1

    def pop(self):
        if not self._heap:
            raise IndexError("pop from an empty priority queue")
        return heapq.heappop(self._heap)[2]

    def peek(self):
        return self._heap[0][2]

    def __len__(self):
        return len(self._heap)

    def __bool__(self):
        return bool(self._heap)

    def __iter__(self):
        return iter([item for _, _, item in sorted(self._heap, reverse=True)])


queue = PriorityQueue()
queue.push("write tests", 1)
queue.push("ship fix", 10)
queue.push("review pr", 5)

while queue:
    print(queue.pop())

Negating the priority converts a max-heap into a min-heap of negatives, and the third element is never compared unless the first two tie. Iterating in sorted order is a convenience that costs a full sort, so it is appropriate for small queues and debugging rather than for hot paths.

Inheriting the protocol from collections.abc

collections.abc defines abstract base classes that encode the protocols the language relies on. Subscribing to Sequence gives you __contains__, __iter__, __reversed__, index, and count on top of just __getitem__ and __len__. Subscribing to Mapping supplies the entire read side of a dictionary. The cost is one registration; the benefit is that you stop reimplementing behavior the standard library already tested.

Base classYou provideYou inheritTypical use
Sequence__getitem__, __len__containment, reversal, index, countRead-only ordered data
MutableSequenceplus __setitem__, __delitem__, insertappend, extend, remove, popList-like types
Mapping__getitem__, __len__, __iter__keys, values, items, equalityRead-only dictionaries
Set__contains__, __iter__, __len__union, intersection, differenceSet algebra without mutation

A registered class is also recognized by isinstance checks in library code, so a custom sequence passed to random.choice or sorted behaves exactly as expected. Where the inherited implementation would be slower than a purpose-built one, override it; the base class is a floor, not a ceiling.

Small containers that already exist

Before writing a collection, check whether collections or itertools already holds it. deque gives O(1) appends and pops at both ends, which is what a bounded buffer or a breadth-first frontier needs; a list cannot offer that because its front operations shift every element. namedtuple and its dataclass cousin make record-like tuples readable without boilerplate. defaultdict removes the get-and-set dance for grouping. ChainMap and Counter each collapse a pattern that otherwise grows into a helper module.

The reason to still write your own is a constraint the standard containers do not satisfy: a bounded history that evicts from the front, a queue with priorities and stable ties, or a view that computes values lazily while preserving identity. In each case the custom type is small because the protocol does the heavy lifting.

The operations you inherit, and what they cost

Inheriting from a sequence base buys a set of methods whose performance follows from the two primitives you supplied. Containment becomes a linear scan built on __getitem__, so testing membership on a custom sequence is O(n) unless you override it with a set-backed implementation. Indexing becomes O(1) only if your __getitem__ is O(1); a linked structure will make random.choice on your sequence quadratic in disguise, because choice indexes a random position after asking for the length.

Slicing is worth a deliberate decision. Python's default behavior for a missing __getitem__ slice support raises a type error, and many custom sequences never define it, which means collection[1:3] fails even though iteration works. Implementing slices as a view object avoids copying while preserving the familiar syntax; implementing them as new lists of the same type is simpler and usually sufficient when the data is already small.

Equality and hashing are another pair of choices. Sequences compare by content, which is convenient in tests and expensive on large data, and they are unhashable because they are mutable. If a collection must be used as a dictionary key, make it immutable, or expose an explicit frozen view that carries only the identity fields. Stating these decisions in the class docstring saves the next caller from discovering them through an exception.

Failure modes worth testing

Custom collections fail in predictable ways. An iterator that returns a new cursor from __iter__ cannot be resumed after an exception mid-loop. A container that defines __getitem__ but no __len__ behaves inconsistently under boolean evaluation. Mutation during iteration either skips elements or raises, so document which behavior you guarantee. And an infinite iterator passed to list() hangs the process, which is why islice belongs in any test that touches a lazy range.

Test each protocol method directly, then test the collection through generic code: a for loop, list(), reversed() when supported, and membership. If it works there, it works everywhere else that matters.

Common Mistakes

Returning self from the container's __iter__ so the cursor is shared

Fix: Return a fresh iterator from the container and only return self from the iterator itself

Comparing equal-priority items directly in a heap tuple

Fix: Insert a monotonic sequence number between the priority and the payload so ties resolve without comparing payloads

Reimplementing index and count when Sequence provides them

Fix: Subclass collections.abc.Sequence and implement only __getitem__ and __len__

Leaving a lazy iterator unconstrained in tests

Fix: Wrap it in islice or drive it with a sentinel so a mistake cannot hang the suite

Best Practices

  • Design the container and its iterator as two types from the start
  • Implement __len__ so boolean checks, reversed, and membership behave for free
  • Check collections and itertools before writing a new data structure
  • Document whether mutation during iteration skips, raises, or snapshots
  • Keep __iter__ on a container O(1); sorting belongs in an explicit method

Interview Questions

Q1: What is the difference between an iterable and an iterator?

An iterable returns a new iterator from __iter__; an iterator produces values from __next__ and raises StopIteration when done. Lists are iterable, list iterators are iterators, and every iterator is also iterable by returning itself.

Q2: Why add a sequence number to a heap entry?

Heap entries are compared lexicographically. Without a tiebreaker, equal priorities fall through to comparing payloads, which may be unorderable and raises TypeError. A counter restores total order.

Q3: What do you inherit by subclassing collections.abc.Sequence?

Containment via linear search, iteration via indexed access, reversal, index, and count. You supply only __getitem__ and __len__, and isinstance checks against Sequence start succeeding.

Key Takeaways

  • The for loop only needs __iter__ and __next__; everything else is convenience
  • Containers produce fresh cursors, iterators are consumed once
  • Priority queues need a tiebreaker so equal priorities never compare payloads
  • collections.abc supplies protocol behavior so you implement only what is unique
  • Test custom collections through generic code paths, not only through their own methods
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement