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

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -