Data Structures22 min read

Custom Iterable Structures

Build your own iterable data structures with __iter__ and __next__, so you can create clean custom containers that work with for-loops naturally.

David Miller
November 16, 2025
4.5k211

Custom iterables let your structure work like a list in a for loop.

Why this matters

In real code you may build:

  • stream readers
  • custom collections
  • data pipelines

Example: custom range-like structure

class MyRange:
    def __init__(self, start, end):
        self.start = start
        self.end = end

    def __iter__(self):
        self.cur = self.start
        return self

    def __next__(self):
        if self.cur >= self.end:
            raise StopIteration
        val = self.cur
        self.cur += 1
        return val

for x in MyRange(3, 7):
    print(x)

Graph: iterator lifecycle

flowchart LR
  A[__iter__] --> B[__next__]
  B --> C[Yield value]
  C --> B
  B --> D[StopIteration]

Remember

  • iter returns iterator object
  • next returns next item
  • StopIteration ends the loop
#Python#Advanced#Iterators