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 list <code>words</code> has three elements. The copy of <code>words</code> also does. You iterate over the copy, insert something in <code>words</code> if the current element is longer than 6 characters, and are done.</p>

<p>Now let's see what happens when you iterate over <code>words</code> directly:</p>

<p>The first two iteration steps are fine, because the condition is False. But since <code>len('blahblah') &gt; 6</code>, you are now inserting <code>'blahblah'</code> at the beginning of the list. Now the list looks like this:</p>

<p><code>['blahblah', 'cat', 'window', 'blahblah']</code></p>

<p>You've just seen the third element, so now the loop continues and looks at the fourth element, but because you inserted something at the beginning of the list the rest of the list shifted and the new fourth element is <code>'blahblah'</code> again. <code>blahblah</code> is still longer than 6 characters, you insert it again in the beginning and are stuck in an infinite loop:</p>

<pre><code>['cat', 'window', 'blahblah']
   ^
['cat', 'window', 'blahblah']
            ^
['cat', 'window', 'blahblah']
                       ^
['blahblah', 'cat', 'window', 'blahblah']
                                   ^
['blahblah', 'blahblah', 'cat', 'window', 'blahblah']
                                               ^
...
</code></pre>

python