Custom Iterator in Python

Implement a class that can be iterated over using __iter__ and __next__.

IntermediateObject-Oriented ProgramsExample 12 of 25
custom-iterator.py
1# Program to implement a custom iterator
2
3class Countdown:
4 def __init__(self, start):
5 self.current = start
6
7 def __iter__(self):
8 return self
9
10 def __next__(self):
11 if self.current <= 0:
12 raise StopIteration
13 value = self.current
14 self.current -= 1
15 return value
16
17for num in Countdown(3):
18 print(num)

Output

3
2
1

What's going on

By defining __iter__ and __next__, Countdown becomes an iterator usable in for-loops.

After this program

If the idea is still fuzzy, read Day 11: Classes and Objects in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 object-oriented programs, or see every topic on Python exercises.