Is It Safe To Change The Iterator Dynamically In Python?
Solution 1:
You are changing the sequence, not the iterator. The for
loop calls iter()
on the object you are looping over, creating a loop iterator. For a list
object, the list iterator created keeps a reference to the original list and an internal index, and every time the for
loop asks for the next item (calls next()
on the iterator), the item at the current index is returned and the index is incremented.
In this case it is safe, as the loop iterator object will happily continue over the extra items. As long as you don't add items to i
indefinitely, the loop will complete.
If you were to remove items from i
, however, the loop iterator would not see those changes and you would get 'surprising' results:
i = [1, 2, 3, 4, 5]
for a in i:
if a == 1:
del i[0]
print a
prints:
1
3
4
5
because the loop iterator yields i[1]
on the next iteration, which is now 3
, not 2
.
Similar problems would occur if you were to insert items before the current iteration index.
You can create the iterator yourself, and experiment manually to see what happens:
>>>i = [1, 2, 3, 4, 5]>>>i_iter = iter(i) # index starts at 0>>>next(i_iter) # now the index is 1
1
>>>del i[0]>>>i
[2, 3, 4, 5] # item at index 1 is 3
>>>next(i_iter) # returns 3, next index is 2
3
>>>i.insert(0, 1)>>>i
[1, 2, 3, 4, 5] # item at index 2 is 3
>>>next(i_iter) # returns 3, next index is 3
3
Post a Comment for "Is It Safe To Change The Iterator Dynamically In Python?"