title: Modifying a list while iterating over it with python
body: <p>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." </p>
  
  <p>Consider the following:</p>
  
  <pre><code>lst = ['a', 'b', 'c', 'd', 'e']
  for x in lst:
      lst.remove(x)
  print(lst)
  </code></pre>
  
  <p>Here is my attempt at explaining what actually happens when one modifies a list while iterating over it. Note that line2 is equivalent to <code>for i in range(len(lst)):</code>, and that <code>len(lst)</code> decreases by 1 with every iteration. </p>
  
  <p><code>len(lst)</code> begins as 5.</p>
  
  <p>When <code>i = 0</code>, we have <code>lst[i] = 'a'</code> being removed, so <code>lst = ['b', 'c', 'd', 'e']</code>. <code>len(lst)</code> decreases to 4.</p>
  
  <p>When <code>i = 1</code>, we have <code>lst[i] = 'c'</code> being removed, so <code>lst = ['b', 'd', 'e']</code>
  <code>len(lst)</code> decreases to 3.</p>
  
  <p>When <code>i = 2</code>, we have <code>lst[i] = 'e'</code> being removed, so <code>lst = ['b', 'd']</code>. <code>len(lst)</code> decreases to 2.</p>
  
  <p>This is where I thought an IndexError would be raised, since <code>i = 2</code> is not in <code>range(2)</code>. However, the program simply outputs <code>['b', 'd']</code>. Is it because <code>i</code> has "caught up" with <code>len(lst)</code>? Also, is my reasoning sound so far?</p>