1

Using python, it is possible to remove elements from a list that you are currently looping on.

Why is it possible ? Why is removing an element from the list while looping on it not causing a problem (breaking indexes, etc. ?) ?

Example code:

ml = ["1","2","3","4","5","6","7","8","9","10"]

for m in ml:
    if m == "5":
        ml.remove("9")
        ml.remove("1")

print(ml)

Output with Python 3.8.3:

['2', '3', '4', '5', '6', '7', '8', '10']

Edit: I am not asking how to remove an element from a list, I am asking why there is no consequence during the rest of the iteration

Edit: Seems like people do not actually read everything during triage...

Better answer is here: Strange result when removing item from a list while iterating over it

Again, I was not asking "How to remove from list", but why is it not causing problems (or at least, in my code example).

Itération 122442
  • 2,644
  • 2
  • 27
  • 73
  • 7
    it actually cause a problem, you just don't see it. – buran Feb 04 '21 at 10:59
  • 1
    you aren't iterating over an index, you are iterating over the list items here. while you CAN do this, you probably should never actually do this. – Nullman Feb 04 '21 at 10:59
  • 2
    It is a problem. Add a `print(m)` before the `if` statement. You will see that 9 doesn't show up, but unfortunately 6 neither because you removed 1 and so shifted all indexes. – BNilsou Feb 04 '21 at 11:07

0 Answers0