I don't understand why the below code doesn't behave the same like the second code snippet:
a = iter(list(range(10)))
for i in a:
print(i)
next(a)
Output:
0
2
4
6
8
Second snippet:
a = list(range(10))
for i in a:
print(i)
a.pop(0)
Output:
0
2
4
6
8
I concluded that in snippet with pop, the for loop keeps track of the index of the list it is iterating over, as first, it prints 0, then it pops 0, and as in the first iteration, i
was assigned to index 0, in the second iteration, however, it should be index 1, which it is. So, it prints whatever is at index 1, which is 2 now, and not 1, as 0 was popped. Etc...
However, in the snippet where we're iterating over an iterator, the behavior doesn't seem to be the same. In the first iteration, it assigns i
to 0, which means it consumed it. Now, after printing i
, we use the next
function, which would return 1 and also consumes it, meaning at index 0 is 2 now. In the second iteration, the for loop would now be at the index of 1, meaning i
should be assigned to 3, and not 2.
I have a idea about why it wouldn't work that way, but I am not certain and would greatly appreciate further explanation:
-As iterators are not subscriptable, they don't have indexes, as far as I know, so the for loop wouldn't work if it would use indexes, unlike when iterating a list, like in the second snippet. Concluding that the for loop would always just use the next item in the iterator, which would mean it would assign i
to 2 in the second iteration, as it did.