0

I know that the following is a suboptimal implementation of a fibonacci generator compared to this, but I cannot seem to understand why it is not working as expected:


def fibonacci_sequence():
    fl, fp = 1, 1
    while True:
        yield (fl + fp)
        store = fl + fp
        fp = fl
        fl = store


for i in range(10):
    print(next(fibonacci_sequence()))

It keeps printing 2 all the time.

Isn't the generator's state being updated underneath yield keyword on each iteration?

pkaramol
  • 16,451
  • 43
  • 149
  • 324

1 Answers1

5

You are instantiating a new generator in each loop iteration. Do instead:

fib = fibonacci_sequence()

for i in range(10):
    print(next(fib))  # keep calling next on the same generator object

To generate the entire sequence from the start, you might want to yield fp instead of yield (fl + fp).

user2390182
  • 72,016
  • 6
  • 67
  • 89