1

I have the following code and it only deletes half the list using a for loop. Why does this happen? Also, how should I delete the first element of the list WHILE traversing through it?

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

Output:

1 
2
3
4
5
[6, 7, 8, 9, 10]
MSeifert
  • 145,886
  • 38
  • 333
  • 352
j.doe
  • 87
  • 6
  • 1
    you're changing the list used in the loop, work on a copy to avoid this – PRMoureu Aug 14 '17 at 21:56
  • 2
    Do not modify a list you are iterating over - your iterator gets screwed up. Also: don't use `list` as a variable name it hides pythons built in `list` type. – AChampion Aug 14 '17 at 21:57
  • Try: `for x in range(len(list)):` instead ;) – Nir Alfasi Aug 14 '17 at 21:58
  • 1
    You should not modify the list when iterating. You should either put the elements to a new list or use list comprehension or `filter` function to filter the list – balki Aug 14 '17 at 21:59
  • Possible duplicate of [Remove items from a list while iterating](https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating) – DYZ Aug 14 '17 at 22:05
  • To support the explanations provided in answers, you can take a look at [the execution of your code](http://www.pythontutor.com/visualize.html#code=list%20%3D%20%5B1,2,3,4,5,6,7,8,9,10%5D%0Afor%20x%20in%20list%3A%0A%20%20%20%20print%20list%5B0%5D%0A%20%20%20%20del%20list%5B0%5D%0Aprint%20list&cumulative=false&curInstr=12&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=2&rawInputLstJSON=%5B%5D&textReferences=false). – Ettore Rizza Aug 14 '17 at 22:10

2 Answers2

3

The problem is that you delete from the list but the list-iterator doesn't know that and happily processes the "remaining" list.

So in the first iteration the iterator is at index 0 and you remove index 0, in the next iteration the iterator returns index 1 (which would be the item at index 2 before you removed the first item) and it removes index 0. In the next iteration you get the item at index 2 (which was at index 4 originally but since you removed two items is now at index 2) and so on. Finally it will stop as soon as the index is greater than the items remaining in the list, given that you remove one item for each item processed that's in the middle (half) of the original list.

Long story short: Don't modify the list you're iterating over.


If you really want to do something like that then you could use a while loop:

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

or iterate over a copy:

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

Note: list is the name of a built-in function of Python, so you would shadow this function if you have a variable with the same name. That's why I changed the variable name to lst.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
3

What is happening here is that you are changing the list as you are iterating over it, lets look at the iterations of the loop

1st iteration:

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

now you delete the number 1 from the list, but THE POINTER WILL STILL MOVE TO THE NEXT ITEM, that is the problem

2nd iteration:

  pointer
     |
     V
 [2, 3, 4, 5, 6, 7, 8, 9, 10]

Next iteration the number 2 will be deleted and the pointer will advance.

3rd iteration:

     pointer
        |
        V
 [3, 4, 5, 6, 7, 8, 9, 10]



4th iteration:

        pointer
           |
           V
 [4, 5, 6, 7, 8, 9, 10]



5th iteration (last one):

           pointer
              |
              V
 [5, 6, 7, 8, 9, 10]

Now you print the list and get [6, 7, 8, 9, 10]. You can see that what I said is in fact really what is going on by changing the line print list[0] to print list[0], x, that way you can see the pointer.

This will be the output:

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

What can be done to fix this problem? any one of the following:

This will make x a number (an index of an item in the list) which means the loop will have len(list) iterations (that would be 10 iterations)

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

for x in range(len(list)):
    print list[0]
    del list[0]
print list 

This will make it so the loop iterates over a copy of the original list, therefore it will loop 10 times, which is enough to delete all the items in the list.

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

for x in copy:
    print list[0]
    del list[0]
print list 
Donat Pants
  • 379
  • 4
  • 11