title: Python loop over iterator of list whose length is changed during the loop
body: <p>Let's say I would like to do the following: I have a list <code>l</code> and at each step I would like to check some condition between <code>l[i]</code> and <code>l[i+1]</code> and if it is satisfied, I will update <code>l[i]</code> based on <code>l[i+1]</code> and delete <code>l[i+1]</code>, then I will check condition between <code>l[i]</code> and former <code>l[i+2]</code> which is now new <code>l[i+1]</code> an so on. If at some step condition is not satisfied, I just do <code>i+=1</code>.</p>
  
  <p>My implementation is as follows:</p>
  
  <pre><code>i = 0
  while i &lt; len(l): 
      if condition(l[i],l[i+1]):
          l[i] = update(l[i+1])
          del l[i+1]
      else:
          i += 1
  </code></pre>
  
  <p>Unfortunately, <code>len(l)</code> is only computed once, and when the <code>while</code> clause is checked, only <code>i</code> changes, not <code>len(l)</code>. Hence, at some moment if I deleted some elements I'd get an error of index being out of range. A similar issue appears when I insert new members of the list while iterating.</p>