list_iterator 垃圾是否收集其消耗的值?

Does a list_iterator garbage collect its consumed values?

假设我有 li = iter([1,2,3,4]).

当我这样做时,垃圾收集器是否会删除对无法访问的元素的引用 next(li)

那么 dequedi = iter(deque([1,2,3,4])) 中的元素在消耗后是否可以收集。

如果没有,Python 中的原生数据结构是否实现了这种行为。

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

在迭代到序列末尾之前,将保留对该列表的引用。您可以在 iternext 函数中看到这一点。

双端队列在这里,没有特殊的迭代器。

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

您可以创建自己的 class 并定义 __iter__ 和 __next__ 来执行您想要的操作。像这样

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) )