Search code examples
pythonlistiterator

How does python iterator for list actually works?


Let's say we have the following list and we are creating an iterator for it:

lst = [1,2,3]
itr = iter(lst)

Next lets say we are changing our list with completely different values:

lst = ['a', 'b', 'c']

And if I we run the following loop:

for x in itr:
   print x

We will get '1,2,3'. But why? As far as I understand, iterator doesn't copy all values from iterating object. At least iterator for list from three elements has the same size as a list of 100000 elements. sys.getsizeof(i) returns 64. How can iterator be so small by size and keep 'old' values of list?


Solution

  • The iterator itself contains a reference to the list. Since lst is rebound instead of mutated, this reference does not change.

    >>> lst = [1, 2, 3]
    >>> itr = iter(lst)
    >>> lst[:] = ['a', 'b', 'c']
    >>> for x in itr:
    ...   print x
    ... 
    a
    b
    c