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