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>When you are doing <code>words[:]</code>, you are iterating over the copy of list, whereas with <code>words</code>, you are iterating over the original copy of list.</p>

<p>In the case <code>II</code>, your interpreter is freezing because when you are at the last index, the condition is satisfied and you insert the item at the beginning of the list. Now, there is one more index which is required to be iterated by the loop. Again, the condition satisfies and it keeps on going like this resulting in an infinite loop.</p>

<p>Where as that is not the case with <code>words[:]</code>, as the list in which you are appending and the one on which you are iterating are different.</p>

python