Implementing __next__()
Lesson 5 of 13 in Coddy's Python Iterators course.
The __next__() method is a crucial part of creating custom iterators in Python. It defines how to retrieve the next item in the iteration sequence. When implementing __next__(), you control the behavior of your iterator, determining what values it produces and when it should stop.
Purpose of __next__()
The __next__() method serves two main purposes:
- Return the next item in the sequence
- Raise a
StopIterationexception when there are no more items
Implementing __next__()
Here's a basic structure for implementing __next__():
class MyIterator:
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
result = self.data[self.index]
self.index += 1
return result
Key Aspects of __next__()
- State Management: Keep track of the current state of iteration (e.g., using an index).
- Return Next Item: Determine and return the next item in the sequence.
- StopIteration: Raise
StopIterationwhen there are no more items. - Side Effects: Update any necessary internal state for the next iteration.
Example: Custom Range Iterator
Here's an example of a custom iterator that mimics a simplified version of Python's range()</function>:</p>
<pre><code class="language-python">class CustomRange:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
result = self.current
self.current += 1
return result
# Using the custom range iterator
for num in CustomRange(1, 5):
print(num) # Outputs: 1, 2, 3, 4
In this example, __next__() returns the current number and increments it for the next iteration, raising StopIteration when it reaches the end value.
By implementing __next__(), you define the core behavior of your iterator, allowing it to work seamlessly with Python's iteration mechanisms like for loops and the next() function.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a custom iterator class called FibonacciIterator that generates Fibonacci numbers up to a specified limit. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones.
You are provided with the following:
- An integer
limitas input
Your FibonacciIterator class should:
- Implement the
__next__()method to generate the next Fibonacci number - Stop the iteration when the next Fibonacci number would exceed the given limit
- Raise a
StopIterationexception when the sequence is exhausted
After implementing the FibonacciIterator class, create an instance of it using the input limit, and print each generated Fibonacci number on a new line.
The input will be provided as a string representing an integer.
Try it yourself
# Read input
limit = int(input())
class FibonacciIterator:
def __init__(self, limit):
self.limit = limit
self.a, self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
# TODO: Implement the __next__() method
# Generate the next Fibonacci number
# Raise StopIteration when the sequence is exhausted
pass
# Create an instance of FibonacciIterator
fib_iterator = FibonacciIterator(limit)
# TODO: Iterate through the Fibonacci sequence and print each number
# Note: Make sure to print each Fibonacci number to pass the test cases