Edit: I know to iterate over a copy of my list when I want to modify the original. However, the only explanation I've ever received on what's wrong with modifying a list while iterating over it is that "it can lead to unexpected results."
Consider the following:
lst = ['a', 'b', 'c', 'd', 'e']
for x in lst:
lst.remove(x)
print(lst)
Here is my attempt at explaining what actually happens when one modifies a list while iterating over it. Note that line2 is equivalent to for i in range(len(lst)):
, and that len(lst)
decreases by 1 with every iteration.
len(lst)
begins as 5.
When i = 0
, we have lst[i] = 'a'
being removed, so lst = ['b', 'c', 'd', 'e']
. len(lst)
decreases to 4.
When i = 1
, we have lst[i] = 'c'
being removed, so lst = ['b', 'd', 'e']
len(lst)
decreases to 3.
When i = 2
, we have lst[i] = 'e'
being removed, so lst = ['b', 'd']
. len(lst)
decreases to 2.
This is where I thought an IndexError would be raised, since i = 2
is not in range(2)
. However, the program simply outputs ['b', 'd']
. Is it because i
has "caught up" with len(lst)
? Also, is my reasoning sound so far?