context not cleaned at the end of a loop containing yield?

MRAB google at mrabarnett.plus.com
Thu Mar 26 19:34:32 CET 2009


TP wrote:
> Hi everybody,
> 
> This example gives strange results:
> 
> ########
> def foo( l = [] ):
> 
>     l2 = l
>     print l2
>     for i in range(10):
>         if i%2 == 0:
>             l2.append( i )
>         yield i
> ########
> 
>>>> [i for i in ut.foo()]
> []
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>> [i for i in ut.foo()]
> [0, 2, 4, 6, 8]
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>> [i for i in ut.foo()]
> [0, 2, 4, 6, 8, 0, 2, 4, 6, 8]
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> ...
> 
> How to explain this behavior? Why l is not [] when we enter again the
> function foo()?
> 
Read http://www.ferg.org/projects/python_gotchas.html#contents_item_6



More information about the Python-list mailing list