0
0
Pythonprogramming~5 mins

Iterator protocol in Python

Choose your learning style9 modes available
Introduction

The iterator protocol lets you go through items one by one in a simple way. It helps you work with collections like lists or custom objects easily.

When you want to loop through items in a list, tuple, or set.
When you create your own object that holds many items and want to make it easy to loop over.
When you want to read data step-by-step, like reading lines from a file.
When you want to save memory by processing items one at a time instead of all at once.
Syntax
Python
class MyIterator:
    def __iter__(self):
        return self

    def __next__(self):
        # return next item or raise StopIteration
        pass

The __iter__ method returns the iterator object itself.

The __next__ method returns the next item or raises StopIteration when done.

Examples
Using built-in iter() to get an iterator from a list and next() to get items one by one.
Python
my_list = [1, 2, 3]
my_iter = iter(my_list)
print(next(my_iter))  # prints 1
print(next(my_iter))  # prints 2
A custom iterator that counts down from a number to 1.
Python
class CountDown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

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

for num in CountDown(3):
    print(num)
Sample Program

This program creates a simple iterator over a list of fruits. It prints each fruit one by one.

Python
class SimpleIterator:
    def __init__(self, data):
        self.data = data
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.index >= len(self.data):
            raise StopIteration
        item = self.data[self.index]
        self.index += 1
        return item

items = ['apple', 'banana', 'cherry']
for fruit in SimpleIterator(items):
    print(fruit)
OutputSuccess
Important Notes

Always raise StopIteration in __next__ when no more items are left.

The for loop automatically calls iter() and next() behind the scenes.

Summary

The iterator protocol uses __iter__ and __next__ methods to loop over items.

It helps process items one at a time, saving memory and making code cleaner.

You can use it with built-in collections or create your own custom iterators.