iter

Peter Otten __peter__ at web.de
Mon Aug 9 12:31:07 EDT 2010


daryn wrote:

> I'm just playing around with the iter function and I realize that I
> can use the iterator returned by it long after the original object has
> any name bound to it.  Example:
> 
>>>>a=[1,2,3,4]
>>>>b=iter(a)
>>>>b.next()
> 1
>>>>a[1]=99
>>>>a[3]=101
>>>>del a
>>>>b.next()
> 99
>>>>b.next()
> 3
>>>>b.next()
> 101
> 
> it seems as if the original object is never being garbage collected
> even though there is no name bound to it.  Does the name bound to the
> iterator object count as a reference to the original object for
> garbage collection purposes?  

The listiterator object internally holds a reference to the list, but 
doesn't make it available to Python code.

> Is there some way to retrieve/manipulate
> the original object via the iterator?

Not without dirty tricks (ctypes).
 
> Just trying to understand how this all works.

If you can read C look here:

http://svn.python.org/view/python/branches/py3k/Objects/listobject.c?revision=81032&view=markup

Peter



More information about the Python-list mailing list