Consider:
>>> lst = iter([1,2,3])
>>> next(lst)
1
>>> next(lst)
2
So, advancing the iterator is, as expected, handled by mutating that same object.
This being the case, I would expect:
a = iter(list(range(10)))
for i in a:
print(i)
next(a)
to skip every second element: the call to next
should advance the iterator once, then the implicit call made by the loop should advance it a second time - and the result of this second call would be assigned to i
.
It doesn't. The loop prints all of the items in the list, without skipping any.
My first thought was that this might happen because the loop calls iter
on what it is passed, and this might give an independent iterator - this isn't the case, as we have iter(a) is a
.
So, why does next
not appear to advance the iterator in this case?