[Tutor] How does this work (iterating over a function)?
Cameron Simpson
cs at zip.com.au
Thu Jul 10 02:38:00 CEST 2014
On 09Jul2014 15:00, steve10brink at comcast.net <steve10brink at comcast.net> wrote:
>I've been learning Python concepts for about 6 months now and was doing okay with most of these. However, I ran into a fairly simple program developed by Mark Pilgrim in his "Dive Into Python" text that puzzles me and am hoping some of you can explain how this works. He is creating the Fibonoci sequence by iterating over a function that has a generator in it (i.e. no return statement).
>The code is as follows:
>
>def fibonacci(max): #using a generator
>a, b = 0, 1
>while a < max:
>yield a
>a, b = b, a+b
Please post in plain text, not HTML. Something is eating your code indentation.
Returning to your question:
>for n in fibonacci(1000):
>print n,
>
>The program works beautifully buy I can't figure out what we are actually iterating with. When the function is called it 'yields' the value a which is then updated to b, etc. But what is the value of 'n' as it iterates through the function? I can understand iterating through lists, strings, range(), etc. but how this iterates through a function is puzzling me. Obviously the answer, n, is the Fibonocci series but by what mechanism does this work? What is the iterable component of a function?
Other have tried to explain, but let me try a different metaphor.
Pretend (or actually try) the fibonacci() function says: "print a" instead of "yield a".
You can see then that it will print the sequence directly.
When you write a generator function (a function with yield statements), what
you get back when you call it is an iterator which iterates over the values the
"yield"s produce.
It is a little like a pipeline: the "for" loop acts as though it is reading the
values from the yields (or prints).
What happens is that when you call "fibonacci", it sets up the function in
memory and _does not run it_.
When the "for" loop iterates, the function runs until it hits a "uyield"
statement. And stalls. The "for" loop gets the yielded value and does whatever.
Next time the for loop iterates the "fibonacci" function runs again, briefly,
until the next "yield".
I hope this helps you visualise the process.
Cheers,
Cameron Simpson <cs at zip.com.au>
More information about the Tutor
mailing list