Search code examples
pythonpython-3.xlistgarbage-collectiondeque

Does a list_iterator garbage collect its consumed values?


Suppose I have li = iter([1,2,3,4]).

Will the garbage collector drop the references to inaccessible element when I do next(li).

And what about deque, will elements in di = iter(deque([1,2,3,4])) be collectable once consumed.

If not, does a native data structure in Python implement such behaviour.


Solution

  • https://github.com/python/cpython/blob/bb86bf4c4eaa30b1f5192dab9f389ce0bb61114d/Objects/iterobject.c

    A reference to the list is held until you iterate to the end of the sequence. You can see this in the iternext function.

    The deque is here and has no special iterator.

    https://github.com/python/cpython/blob/master/Modules/_collectionsmodule.c

    You can create your own class and define __iter__ and __next__ to do what you want. Something like this

    class CList(list):
        def __init__(self, lst):
            self.lst = lst
    
        def __iter__(self):
            return self
    
        def __next__(self):
            if len(self.lst) == 0:
                raise StopIteration
            item = self.lst[0]
            del self.lst[0]
            return item
    
        def __len__(self):
          return len(self.lst)
    
    
    l = CList([1,2,3,4])
    
    for item in l:
      print( len(l) )