I know that there are better ways of doing this and it is actually not what I want to do, but I'm wondering why it does not work?
x = [13, 3开发者_运维问答, 9, 41]
for i in x:
x.remove(i)
print(x)
[3, 41]
Shouldn't the list be empty?
You should not modify a list in a loop, try this:
x = [13, 3, 9, 41]
for i in x[:]:
x.remove(i)
print(x)
This will loop over a copy of x
but remove elements from x
.
This is a duplicate of Python strange behavior in for loop or lists, you can find more thorough explanations there.
See Python wont remove items from list
精彩评论