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><code>words[:]</code> means a new copy of the <code>words</code> and length is fixed. So you are iterating over a fixed list.</p>

<p>But in the second situation, iterating over and extending the same list which makes it infinity.</p>

<pre><code>words = ['cat', 'window', 'blahblah']
new_words = [_ for _ in words if len(_) &gt; 6]
print(new_words)
</code></pre>

python