Looping over a slice copy of a list
<p>I am trying to understand the difference between <strong>looping over a list</strong> and <strong>looping over a "slice" copy of a list</strong>.</p>

<p>So, for example, in the following list, the element whose length is greater than 6 is appended to the beginning of the list:</p>

<pre><code>words = ['cat', 'window', 'blahblah']

for word in words[:]:
    if len(word) &gt; 6:
        words.insert(0, word)

print(words)

words = ['blahblah', 'cat', 'window', 'blahblah']
</code></pre>

<p>I, then, run the following to see why it is not the correct way of doing it, but my interpreter freezes and I have to exit. Why does this happen? I am simply appending something to the start of my list which is allowed since lists are mutable...</p>

<pre><code>for word in words:
    if len(word) &gt; 6:
        words.insert(0, word)
</code></pre>

<p>Could someone please help me understand why this last bit stops my program?</p>

<p>The following loop</p>

<pre><code>for word in words:
    // do something
</code></pre>

<p>is roughly equivalent to the following one (when <code>words</code> is a list and not another kind of <code>iterable</code>):</p>

<pre><code>i = 0
while i != len(words):
    word = words[i]
    // do something (assuming no 'continue' here)
    i += 1
</code></pre>

<p>Therefore, when while looping you insert something into your list <em>before the current position</em>, then during the next iteration you end up handling the same element as for the previous iteration. In your case this results in an infinite loop.</p>

python