3

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.

1
  • The list iterator itself holds no references to the the individual elements in the list. It's essentially a loop over the indices. The list itself is still referenced by the iterator, at least until it is exhausted. So there will be at least one reference alive to each of the elements in the list until the list itself is reclaimed Commented Feb 13, 2019 at 2:15

1 Answer 1

2

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) )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.