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
December 21, 2025
0.0k0

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 ```python 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 ```mermaid 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