0

I'm getting an error I don't understand, namely, 9 is not being removed from my list:

new_list = [4,6,9,8]

for j in new_list:
    if j * 2 >= 10:
        new_list.remove(j)

print new_list

>> [4, 9]
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Mike
  • 201
  • 2
  • 14

2 Answers2

1

As pointed out by @blhsing you can't mutate a list you are iterating over, as you will get unpredictable results. You can , however, use a list comprehension to construct a new list, e.g.:

old_list = [4,6,9,8]
new_list = [j for j in old_list if j*2 < 10]
AChampion
  • 29,683
  • 4
  • 59
  • 75
  • Well, the results are entirely predictable, and you *can* do it using various approaches (iterating backwards, iterate over indices and take care to adjust the index after mutation, etc). – juanpa.arrivillaga Jul 06 '18 at 05:07
  • I should have been more general, for `list` it maybe predictable. But it is undefined for other data structures and doesn't work for others, like `set` where a `RuntimeError` is generated. [I found a comment by rhettinger that says modifying a `list` iterator is defined but I can't find it in the docs]. – AChampion Jul 06 '18 at 12:17
0

You can't mutate the list you're iterating with. Use a copy of it instead:

new_list = [4,6,9,8]

for j in new_list[:]:
    if j * 2 >= 10:
        new_list.remove(j)

print new_list

This outputs:

[4]
blhsing
  • 91,368
  • 6
  • 71
  • 106