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.