Why does python remove behave like that?

By : ierax
Source: Stackoverflow.com
Question!

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?

By : ierax


Answers
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.





This video can help you solving your question :)
By: admin