Build a Range-Like Iterator
Advanced · Write the code · from Python Iterators: How for Loops Really Work Under the Hood
From the lesson: How Do You Build a Custom Iterator Class?
Now for the fun part. You can make any object iterable by adding __iter__() and __next__() methods to its class. This is like building your own vending machine - you decide what comes out and in what order.
Read this part of the lessonCreate a class called EvenRange that iterates over even numbers from start up to (but not including) stop. It should work like this:
for n in EvenRange(2, 10):
print(n)
# Output: 2 4 6 8Implement __iter__ and __next__ methods. If start is odd, begin from the next even number.
class EvenRange:
def __init__(self, start, stop):
# Make sure we start on an even number
pass
def __iter__(self):
pass
def __next__(self):
pass
# Test it
for n in EvenRange(2, 10):
print(n)
More Iterator exercises
- Manual Iteration with next()Intermediate
- Fix the Broken IteratorIntermediate
- Cycle Through TeamsIntermediate
- Build a Fibonacci IteratorAdvanced
- Chain and Filter with itertoolsAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz