[Tutor] How does this work (iterating over a function)?

Raúl Cumplido raulcumplido at gmail.com
Wed Jul 9 21:19:02 CEST 2014


Yes, every generator is an iterator (but not viceversa) and you can iterate
over an iterator.

An iterator is one object that implements the Python iterator protocol.

Thanks,
Raúl


On Wed, Jul 9, 2014 at 7:59 PM, <steve10brink at comcast.net> wrote:

>
>
> ------------------------------
>
> I guess my higher level question is: "what makes this function iterable?"
> and the answer appears to be the fact that it
> uses a generator instead of a return function.  Is that correct?
>
> -Steve Tenbrink
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Wed, 9 Jul 2014 16:24:46 +0100
> From: Ra?l Cumplido <raulcumplido at gmail.com>
> To: steve10brink at comcast.net
> Cc: tutor <tutor at python.org>
> Subject: Re: [Tutor] How does this work (iterating over a function)?
> Message-ID:
>         <CAD1Rbrou1hDfxkBeJcB97361uwyNYq8tW7REk=
> mhUaVjeNNk2g at mail.gmail.com>
> Content-Type: text/plain; charset="utf-8"
>
>
> Hi,
>
> A little bit more on this :)
>
> Python iterator protocol will call the next() method on the iterator on
> each iteration and receive the values from your iterator until a
> StopIteration Exception is raised. This is how the for clause knows to
> iterate. In your example below you can see this with the next example:
>
> >>> gen = fibonacci(3)
> >>> gen.next()
> 0
> >>> gen.next()
> 1
> >>> gen.next()
> 1
> >>> gen.next()
> 2
> >>> gen.next()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> StopIteration
> >>>
>
> Thanks,
> Ra?l
>
>
>
>
>
> --
> Ra?l Cumplido
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: <
> http://mail.python.org/pipermail/tutor/attachments/20140709/ccbbee12/attachment-0001.html
> >
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Raúl Cumplido
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140709/954d6ced/attachment.html>


More information about the Tutor mailing list