pythonintermediate

Implement the Iterator Protocol

Create custom iterators using __iter__ and __next__ for lazy evaluation.

python
class Countdown:
    """Custom iterator that counts down from n."""
    def __init__(self, start: int):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        value = self.current
        self.current -= 1
        return value

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

# Generator-based (simpler)
def chunked(iterable, size):
    """Yield successive chunks of a given size."""
    chunk = []
    for item in iterable:
        chunk.append(item)
        if len(chunk) == size:
            yield chunk
            chunk = []
    if chunk:
        yield chunk

data = list(range(10))
for batch in chunked(data, 3):
    print(batch)  # [0,1,2], [3,4,5], [6,7,8], [9]

Use Cases

  • Batch processing
  • Lazy data loading
  • Custom sequences

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.