开发者

Why does python remove behave like that?

开发者 https://www.devze.com 2023-02-17 17:35 出处:网络
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?

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

精彩评论

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