1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Oh, so calling fib(10) several times is not the same as calling f several times?
Every time you call fib(10) you are calling an entirely new function, but when you call f you are calling a single instance of fib(10)
Ok, that explains it.
@MichaelSB I am glad it made sense!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.