python - Why does del list[0] in a for-loop only delete half the list? -


i have following code , deletes half list using loop. why happen? also, how should delete first element of list while traversing through it?

list = [1,2,3,4,5,6,7,8,9,10] x in list:     print list[0]     del list[0] print list  

output:

1  2 3 4 5 [6, 7, 8, 9, 10] 

the problem delete list list-iterator doesn't know , happily processes "remaining" list.

so in first iteration iterator @ index 0 , remove index 0, in next iteration iterator returns index 1 (which item @ index 2 before removed first item) , removes index 0. in next iteration item @ index 2 (which @ index 4 since removed 2 items @ index 2) , on. stop index greater items remaining in list, given remove 1 item each item processed that's in middle (half) of original list.

long story short: don't modify list you're iterating over.


if want use while loop:

lst = [1,2,3,4,5,6,7,8,9,10] while lst:   # long lst contains items     print lst[0]     del lst[0] print lst  

or iterate on copy:

lst = [1,2,3,4,5,6,7,8,9,10] x in lst[:]:   # [:] makes shallow copy of list     print lst[0]     del lst[0] print lst  

note: list name of built-in function of python, shadow function if have variable same name. that's why changed variable name lst.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -