Reputation: 3181
I'm learning about generators, so I defined the following function which calculates Fibonacci sequence:
def fib(max):
a, b = 0, 1
while a < max:
yield a
a, b = b, a + b
I tried to use it like this, but it didn't work:
next(fib(10))
Out[413]: 0
next(fib(10))
Out[414]: 0
next(fib(10))
Out[415]: 0
However, using it like this works as expected:
f = fib(10)
next(f)
Out[417]: 0
next(f)
Out[418]: 1
next(f)
Out[419]: 1
next(f)
Out[420]: 2
Why the first case does not work?
Upvotes: 1
Views: 65
Reputation: 1467
next(iterator[, default])
Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
The first one works:
It just generates a new iterator
for each of the functions instances you make when you callfib(10)
So, every time you call fib(10)
you create a new fib function instance that returns an iterator
specific to that instance.
Notice that they all return the first value correctly.
Upvotes: 2
Reputation: 1173
when you run it in the first case it starts again from the beginning and so it'll always just go start --> first, while in the second case everytime you call f, f is changing so it goes start --> first --> second --> third.
Upvotes: 0