Python6 min read

Python Iterators and Iterables

Create custom iterators and iterables.

David Miller
December 18, 2025
0.0k0

Build custom iteration logic.

Custom Iterator

```python class Counter: def __init__(self, max): self.max = max self.current = 0 def __iter__(self): return self def __next__(self): if self.current < self.max: self.current += 1 return self.current raise StopIteration

for num in Counter(5): print(num) # 1, 2, 3, 4, 5 ```

Iterable Class

```python class Fibonacci: def __init__(self, max): self.max = max def __iter__(self): self.a = 0 self.b = 1 self.count = 0 return self def __next__(self): if self.count < self.max: result = self.a self.a, self.b = self.b, self.a + self.b self.count += 1 return result raise StopIteration

for num in Fibonacci(10): print(num) # 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ```

Reverse Iterator

```python class Reverse: def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def __next__(self): if self.index == 0: raise StopIteration self.index -= 1 return self.data[self.index]

for char in Reverse("hello"): print(char) # o, l, l, e, h ```

Iterator with __getitem__

```python class MyRange: def __init__(self, start, end): self.start = start self.end = end def __getitem__(self, index): if index >= self.end - self.start: raise IndexError return self.start + index

for num in MyRange(0, 5): print(num) # 0, 1, 2, 3, 4 ```

Remember

- __iter__ returns iterator - __next__ returns next item - Raise StopIteration when done

#Python#Advanced#Iterators