Python list insertion when iterating
<p>I'm working with python 3.5, and insert isn't behaving as I expect it to.</p>

<pre><code>scorelist = ["x","x"]

for q in range(0, len(scorelist)):
    if scorelist[q] == "x":
        scorelist.insert((q), " ")
</code></pre>

<p>I'd expect that to leave the least reading as follows</p>

<pre><code>scorelist = ["x", " ", "x", " "]
</code></pre>

<p>Instead, it leaves me with</p>

<pre><code>scorelist = [" ", " ", "x", "x"]
</code></pre>

<p>I'm pretty stumped as to why this is the output. Any guidance would be greatly appreciated.</p>

<p>It's generally a Bad Idea to mutate any container while iterating over it.</p>

<p>In your case, <code>len(scorelist)</code> is evaluated once, at the time the <code>for</code> loop begins.  The length is 2 at that time, so the range is just <code>[0, 1]</code>.  Nothing later can possibly change that.</p>

<p>In the first iteration, <code>q</code> is 0, and <code>scorelist[0]</code> is <code>"x"</code>, so</p>

<pre><code>scorelist.insert(0, " ")
</code></pre>

<p>leaves <code>scorelist</code> as</p>

<pre><code>[" ", "x", "x"]
</code></pre>

<p>In the second iteration, <code>q</code> is 1, and for the new value of <code>scorelist</code>, <code>scorelist[1]</code> is still <code>"x"</code>, so</p>

<pre><code>scorelist.insert(1, " ")
</code></pre>

<p>leaves <code>scorelist</code> as</p>

<pre><code>[" ", " ", "x", "x"]
</code></pre>

<p>Then the loop ends.  There's nothing really mysterious about it, but it's far from obvious either - which is <em>why</em> it's a Bad Idea to mutate containers while iterating over them ;-)</p>

<h2>EDIT: GETTING WHAT YOU WANT</h2>

<p>If you're determined to insert a blank at the end, and between every pair of elements before that, here's one obscure way to do it:</p>

<pre><code>for q in reversed(range(1, len(scorelist) + 1)):
    scorelist.insert(q, " ")
</code></pre>

<p>Then, e.g., if <code>scorelist</code> starts as</p>

<pre><code>['x', 'y', 'z']
</code></pre>

<p>that loop will leave it as</p>

<pre><code>['x', ' ', 'y', ' ', 'z', ' ']
</code></pre>

<p>By iterating "backwards", the insertions don't interfere with the original indices of the original list elements.  If that's confusing (hint: it is! ;-) ), just work it out one iteration at a time, as I spelled it out for your original code.</p>

python