Strange behavior modifying a list while looping over it (Python) -
i understand modifying while iterating can spell disaster. curious tried it. in first few situations below things go expected. happened in second last one? why presence of fifth 0 (the 1 @ end), cause earlier 0 removed??
>>> = [0, 0, 0, 0] >>> k in a: if k == 0: a.remove(k) >>> [0, 0] >>> = [0, 0, 0, 0, 1] >>> k in a: if k == 0: a.remove(k) >>> [0, 0, 1] >>> = [0, 0, 0, 0, 1, 1] >>> k in a: if k == 0: a.remove(k) >>> [0, 0, 1, 1] >>> = [0, 0, 0, 0, 1, 1, 0] >>> k in a: if k == 0: a.remove(k) >>> [0, 1, 1, 0] >>> = [0, 0, 0, 0, 1, 1, 2] >>> k in a: if k == 0: a.remove(k) >>> [0, 0, 1, 1, 2]
edit! somelist.remove(x) removes first occurrence of x. knew that, forgot completely.
i not python expert, when imagine how foreach loop implemented:
len = size(array) in range(0, len): loop_body(array[i])
then second example:
len = 5, array=[0, 0, 0, 0, 1]
first iteration: i=0, array=[0, 0, 0, 0, 1], 0 in array[0] removed.
second iteration: i=1, array=[0, 0, 0, 1], 0 in array[1] removed.
third iteration: i=2, array=[0, 0, 1], array[2] == 1, nothing happened.
and result. same last one.
Comments
Post a Comment