Steven D'Aprano <[email protected]> added the comment:
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.
----------
nosy: +steven.daprano
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue41774>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com