Content · Programming · Python

Python Iterator Protocol: Implement __iter__ and __next__

Implement the iterator protocol with __iter__() and __next__().

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Implement the iterator protocol with __iter__() and __next__().

What You Will Learn


An iterator returns itself from __iter__() and advances in __next__(). When no values remain, __next__ raises StopIteration, which for loops handle automatically.

Containers can create a fresh iterator in each __iter__ call instead of being iterators themselves.

Many iterator tools are lazy. Creating the iterator does not necessarily perform the work; advancing it can consume the original source.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

class SequenceCounter:
    def __init__(self, maximum):
        self.current_value = 0
        self.maximum = maximum

    def __iter__(self):
        return self

    def __next__(self):
        if self.current_value >= self.maximum:
            raise StopIteration
        self.current_value += 1
        return self.current_value

print(list(SequenceCounter(3)))

How the Example Works


  • The class SequenceCounter groups data and behavior; its methods run when called on an instance.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

For the chosen input, the expression list(SequenceCounter(3)) prints [1, 2, 3]. Compare that result with the rule above before you change the argument.

Expected output from the example:

[1, 2, 3]

When You Would Use This


This pattern is useful in readers for CSV files, event streams, or paginated API results, where collecting everything in memory is unnecessary. Because iterator state advances when values are consumed, decide whether you need a reusable collection or a one-time pass. Keep files and connections open until their lazy consumers finish.

Practice: Modify the Code


Implement an iterator that yields even numbers up to a limit.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Returning None when exhausted instead of raising StopIteration.
  • Expecting a consumed iterator instance to begin again on its second pass.

Key Takeaways


  • Implement the iterator protocol with __iter__() and __next__().
  • An iterator returns itself from __iter__() and advances in __next__().
  • Containers can create a fresh iterator in each __iter__ call instead of being iterators themselves.
Share this resourceSend this page to someone who may find it useful.