Search⌘ K
AI Features

Solution Review: Create a Fibonacci Iterator

Understand how to build a Fibonacci sequence iterator by defining __init__, __iter__, and __next__ methods in a class. This lesson teaches how to manage instance variables to track current and next values, allowing seamless iteration over the Fibonacci sequence with lazy evaluation.

We'll cover the following...

Implementation

Python 3.8
class Fibonacci():
def __init__(self):
self.c = 0
self.n = 1
def __iter__(self):
return self
def __next__(self):
ret = self.c
self.c, self.n = self.n, self.c + self.n
return ret
for i in Fibonacci():
print(i)
if i > 100:
break

Explanation

As we learned previously, an iterator is just a class that implements the iterator protocol, i.e., a __next__ method and an __iter__ method. Therefore, we implement both of these methods on line 9 and 6, respectively.

In the __init__ method (lines 2-4), we ...