Generator using item[n-1] + item[n] memory

Mark Lawrence breamoreboy at yahoo.co.uk
Sat Feb 15 07:28:53 EST 2014


On 15/02/2014 03:31, Nick Timkovich wrote:
> OK, now the trick; adding `data = None` inside the generator works, but
> in my actual code I wrap my generator inside of `enumerate()`, which
> seems to obviate the "fix".  Can I get it to play nice or am I forced to
> count manually. Is that a feature?
>
>
> On Fri, Feb 14, 2014 at 9:21 PM, Roy Smith <roy at panix.com
> <mailto:roy at panix.com>> wrote:
>
>     In article <mailman.6952.1392433921.18130.python-list at python.org
>     <mailto:mailman.6952.1392433921.18130.python-list at python.org>>,
>       Nick Timkovich <prometheus235 at gmail.com
>     <mailto:prometheus235 at gmail.com>> wrote:
>
>      > Ah, I think I was equating `yield` too closely with `return` in
>     my head.
>      >  Whereas `return` results in the destruction of the function's
>     locals,
>      > `yield` I should have known keeps them around, a la C's `static`
>     functions.
>      >  Many thanks!
>
>     It's not quite like C's static.  With C's static, the static variables
>     are per-function.  In Python, yield creates a context per invocation.
>     Thus, I can do
>
>     def f():
>          for i in range(10000):
>              yield i
>
>     g1 = f()
>     g2 = f()
>     print g1.next()
>     print g1.next()
>     print g1.next()
>     print g2.next()
>     print g1.next()
>
>
>     which prints 0, 1, 2, 0, 3.  There's two contexts active at the same
>     time, with a distinct instance of "i" in each one.
>     --
>     https://mail.python.org/mailman/listinfo/python-list
>

Nick, please don't top post on this list, thanks.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection is active.
http://www.avast.com





More information about the Python-list mailing list