0

I have just got a strange result in following code.

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

for i in mylist:
    mylist.remove(i)

print (mylist)

It generated [2, 4, 6, 8, 10] somehow. I would use "clear()" if I want to remove all. But, I am just interested in what is going on. Have I done something wrong for system preferenece? thank you for your help.

Koji Sugano
  • 59
  • 1
  • 8
  • Oops, thank you for letting me know this question is duplicate. I am going to check it. – Koji Sugano May 05 '16 at 10:28
  • Refer to the note in the [for loop documentation](https://docs.python.org/2/reference/compound_stmts.html#for) as pointed out in one of the answers of the duplicate – Francesco May 05 '16 at 10:28

1 Answers1

-1

Just for future reference, when using Python 2.7 this is the explanation you are looking for:

There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop.

lesingerouge
  • 1,160
  • 7
  • 14