0

I have the simplest loop to remove items from a list, and when I loop through the list items and print them, it works as expected. However, when I try to use the builtin remove() (list.remove(x)) I get unexpected results:

>>> data = [1, 2, 3, 4, 5]

>>> for i in data:
        print(i)
1
2  
3
4 
5

>>> for i in data:
        data.remove(i)

>>>> data
[2, 4]

What is going on here? Shouldn't my list be empty?

Edit: I don't think the answer to my specific question of why this occurs has been answered. My question asks why the behavior is being experienced, while the other related questions are asking how to properly iterate through a loop. I feel there is something to learn here that a novice programmer might not understand in reading the related questions. If there is a question out there that demonstrates what I wrote in my answer, then by all means mark this as a duplicate.

LegendaryDude
  • 562
  • 8
  • 23
  • You shouldn't remove elements from a data structure when using iterators like this. Although this won't throw a runtime error in Python, some languages won't even allow this behavior. – JNYRanger Mar 02 '15 at 20:23
  • There are other good reasons for not doing it this way, as I have just discovered. I explained in my answer below. – LegendaryDude Mar 02 '15 at 20:25

1 Answers1

1

I have made a logical error. When my loop removes the first entry in the list, the second entry moves to index 1 from 2, and the third entry moves to index 2 from 3. Because '2' is now in index 1 of the list, it doesn't get removed, as the loop has already passed on from index 1 of the list.

LegendaryDude
  • 562
  • 8
  • 23