1

I'm using remove() to delete element from list but the loop is skipping few elements. Below is the code:

m=[14,24,24,7,82,85,82,4,60,95]
for i in m:
    print(i)
    m.remove(i)

The outcome of the above code is: 14 24 82 82 60. Which means that only the printed elements are removed.

After the code execution, m is [24, 7, 85, 4, 95], whereas it should be null. Can somebody explain this?

  • https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating – pault Dec 29 '20 at 04:51
  • I'll try to explain to you. when you remove an element from the array, the next element goes to its position, and the index with which you iterate goes further and will not affect the element that moved – crackanddie Dec 29 '20 at 04:54
  • Suppose that we have a ***list*** named `lystie`. `lystie.remove(22)` deletes the left-most occurrence of `22` inside of `lystie`. The `remove()` method does ***NOT*** delete ***all*** occurrences of `22`. If you have 5 or 6 copies of the word "egg" inside of a list, then the remove() method will only delete ***one*** of the five copies of the word "egg". `remove()` will delete the left-most "egg" from the list. – Toothpick Anemone Dec 29 '20 at 05:01

0 Answers0