This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author steven.daprano
Recipients eric.smith, sreedevi.ha, steven.daprano
Date 2020-09-12.16:53:36
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1599929616.2.0.662185584382.issue41774@roundup.psfhosted.org>
In-reply-to
Content
You say:

"output should be empty list"

but that's not actually correct. You intend the output to be the empty list, but if you think carefully about what happens during iteration, you should see that the behaviour is correct.

To make it easier to see what is happening, let's use different values:

L = [20, 21, 22]


On the first iteration, the interpreter looks at position 0, which is 20. You remove 20 from the list, which shrinks the list down to:

L = [21, 22]

Now it is 21 in position 0. But that iteration of the loop is finished, so the interpreter looks at position 1, which is 22. You remove 22 from the list, giving:

L = [21]

and the interpreter looks at position 2, which does not exist, so the loop finishes.


>>> L = [20, 21, 22]
>>> for i in L:
...     L.remove(i)
...     print('i', i, 'L is now:', L)
... 
i 20 L is now: [21, 22]
i 22 L is now: [21]
>>> L
[21]


So the interpreter did exactly what you told it to do. The problem is that what you told it to do is not what you wanted it to do.
History
Date User Action Args
2020-09-12 16:53:36steven.dapranosetrecipients: + steven.daprano, eric.smith, sreedevi.ha
2020-09-12 16:53:36steven.dapranosetmessageid: <1599929616.2.0.662185584382.issue41774@roundup.psfhosted.org>
2020-09-12 16:53:36steven.dapranolinkissue41774 messages
2020-09-12 16:53:36steven.dapranocreate