title: Can the order of elements in a list cause a bug in a for loop?
body: <p>I'm playing with a simple script to escape certain HTML characters, and am encountering a bug which seems to be caused by the order of elements in my list <code>escape_pairs</code>. I'm not <a href="https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python">modifying the lists</a> during a loop, so I can't think of any Python/programming principles I'm overlooking here.</p>
  
  <pre><code>escape_pairs = [("&gt;", "&amp;gt;"),("&lt;","&amp;lt;"),('"',"&amp;quot;"),("&amp;","&amp;amp;")]
  
  def escape_html(s):
      for (i,o) in escape_pairs:
          s = s.replace(i,o)
      return s
  
  print escape_html("&gt;")
  print escape_html("&lt;")
  print escape_html('"')
  print escape_html("&amp;")
  </code></pre>
  
  <p>returns</p>
  
  <pre><code>&amp;amp;gt;
  &amp;amp;lt;
  &amp;amp;quot;
  &amp;amp;
  </code></pre>
  
  <p>However when I switch the order of the elements in my <code>escape_pairs</code> list to the bug disappears</p>
  
  <pre><code>&gt;&gt;&gt; escape_pairsMod = [("&amp;","&amp;amp;"),("&lt;","&amp;lt;"),('"',"&amp;quot;"),("&gt;", "&amp;gt;")]
  
  &amp;gt;
  &amp;lt;
  &amp;quot;
  &amp;amp;
  </code></pre>