0

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?

sakisk
  • 1,807
  • 1
  • 24
  • 30
  • possible duplicate of [Python strange behavior in for loop or lists](http://stackoverflow.com/questions/742371/python-strange-behavior-in-for-loop-or-lists) – Lennart Regebro Mar 20 '11 at 07:40

2 Answers2

1

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.

Community
  • 1
  • 1
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • Thanks. Is the behavior of `remove` when the original list is used undefined? Because it works in some cases and doesn't work in other cases. It would be nice if it didn't work at all (or at least it could generate a warning, exception, etc.). – sakisk Mar 19 '11 at 21:51
1

See Python wont remove items from list

Community
  • 1
  • 1
Ptival
  • 9,167
  • 36
  • 53
  • 1
    also, if you want to remove elements of a list based on a predicate, you'd rather use list comprehensions: mylist = [e for e in mylist if predicate(e)] – Ptival Mar 19 '11 at 21:41