CodeBlanks Logo Icon CodeBlanks

__iter__ and __next__

Learn iterability with __iter__ and __next__.

__iter__ and __next__

To make a class usable in a for loop, define the __iter__ and __next__ methods. __iter__ returns an iterator; __next__ gives the next item.

Example: class Counter:\n def __iter__(self):\n return self\n def __next__(self):\n .... Writing for n in c first calls __iter__, then __next__ at each step. When items run out, __next__ raises StopIteration; the loop ends.

The for loop flow

Writing for n in c works like this: first iter(c) calls __iter__; on the returned iterator, next() calls __next__ at each step. When StopIteration is raised, the loop ends.

Example: Counter(3) gives three items. for n in Counter(3): print(n) prints 0, 1, 2. Each next() returns a value; on the fourth call StopIteration is raised. This protocol is the same for all iterators.

Practice Add an iterator to Counter

Define the Counter class. Add def __init__(self, limit): with self.limit = limit and self.current = 0 in the body. Add def __iter__(self): with return self. Add def __next__(self):; in the body write if self.current >= self.limit:, raise StopIteration, then value = self.current, self.current += 1 and return value. Then call c = Counter(3) and for n in c: print(n).

Starter code

main.py
# Define the Counter class

Sample solution

main.py
# Define the Counter class
class Counter:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.current >= self.limit:
            raise StopIteration
        value = self.current
        self.current += 1
        return value

c = Counter(3)
for n in c:
    print(n)

Expected output

0
1
2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does __next__ raise when items run out?

  • ValueError
  • TypeError
  • IndexError
  • StopIteration Correct answer

Explanation: StopIteration signals the end of the loop.

2 Complete the __iter__ body

Question
    def __iter__(self):
        return ____
Answer
    def __iter__(self):
        return self

Explanation: When the class is its own iterator, __iter__ returns self.

3 Match the iterator methods

Term Meaning
__iter__ Returns iterator
__next__ Next item
StopIteration Loop end

All lessons in Intermediate