Why converting iterator to list move iterator to last index

Question:

It seems that converting iter. to list move the iter index to last element, why ?

l = iter([1, 2, 3])
x = list(l)
print l.next()

Error message:

Traceback (most recent call last):
print l.next()

StopIteration

Asked By: anati

||

Answers:

Because firstly, you are creating a new object. Secondly an iterator object doesn’t have all it’s item in memory it generates the item on demand, and once you got to the end there is no way back. That’s why they call it one shot iterable. Therefor when you call the list on an iterator you are creating new list object by consuming the iterator and preserving its items in a list.

For a better demonstration it does something like following:

In [8]: l = iter([1, 2, 3])

In [9]: x = [item for item in l]

In [10]: x
Out[10]: [1, 2, 3]
Answered By: Mazdak
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.