Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Unbound iterator Fibonacci

Now we can get back to our original problem, the slightly more complex Fibonacci series. In this example we created an unbounded iterator that on every iteration will return the next element of the Fibonacci series.

class Fibonacci():
    def __init__(self):
        self.values = []

    def __iter__(self):
        return self

    def __next__(self):
        if len(self.values) == 0:
            self.values.append(1)
            return 1

        if len(self.values) == 1:
            self.values.append(1)
            return 1

        self.values.append(self.values[-1] + self.values[-2])
        self.values.pop(0)

        return self.values[-1]
from fibonacci import Fibonacci
for v in Fibonacci():
    print(v)
    if v > 10:
        break

Output:

1
1
2
3
5
8
13