How do I create and use custom iterators in Python?
Implement the `__iter__()` and `__next__()` methods in a class to create a custom iterator. This allows your objects to be iterable in a for loop or other contexts.
Creating custom iterators in Python is a straightforward process that involves defining a class with the __iter__()
and __next__()
methods. The __iter__()
method should return the iterator object itself, while the __next__()
method should return the next value from the iteration. When there are no more items to return, __next__()
should raise a StopIteration
exception to signal that the iteration is complete. Here’s a simple example of a custom iterator that generates Fibonacci numbers:
class FibonacciIterator:
def __init__(self):
self.a, self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
if self.a > 100:
raise StopIteration
self.a, self.b = self.b, self.a + self.b
return self.a
With this setup, you can use your iterator in a for loop, allowing it to generate Fibonacci numbers up to 100. By implementing custom iterators, you can create objects that behave like iterable collections, providing greater flexibility and control over iteration in your Python applications.