PEP 342 misunderstanding

Fredrik Lundh fredrik at pythonware.com
Sun Oct 8 15:47:43 EDT 2006


metamoof at gmail.com wrote:

>>>> def printrange():
> ...     for x in range(10):
> ...         x = yield x
> ...         print x
> ...
>>>> g = printrange()
>>>> for x in g:
> ...     g.send(x*2)
> ...
> 0
> 1
> None
> 4
> 3
> None
> 8
> 5
> None
> 12
> 7
> None
> 16
> 9
> None
> 
> Now, I was expecting that to be 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20.
> 
> What am I missing here?

the output doesn't match your sample program; I assume you left out a 
print statement or two from the second loop.

what you seem to be missing is that "next" (which is called by the 
for-in loop) is basically the same thing as "send(None)".  in other
words, you end up pulling two items from the generator for each iteration.

</F>




More information about the Python-list mailing list