开发者

Why does python remove behave like that?

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜