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

Roy Smith roy at
Sat Feb 15 04:21:11 CET 2014

In article <mailman.6952.1392433921.18130.python-list at>,
 Nick Timkovich <prometheus235 at> 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()

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.

More information about the Python-list mailing list