Incomplete list pop in list comprehention
<p>I have been trying to <code>pop</code> elements in list comprehention using <code>takewhile</code> function and I came into things that is for me hard to understand. My terminal session looks like this:</p>

<p><a href="https://i.stack.imgur.com/yMiBB.png" rel="nofollow"><img src="https://i.stack.imgur.com/yMiBB.png" alt="enter image description here"></a></p>

<p>However when i tried the same thing with strings then problem didn't occur:</p>

<p><a href="https://i.stack.imgur.com/yiA53.png" rel="nofollow"><img src="https://i.stack.imgur.com/yiA53.png" alt="enter image description here"></a></p>

<p>Can someone explain to me that happened in the first scenario? Why <code>g.pop(0)</code> has returned only <code>[1, 2]</code>?</p>

<p>Transcript for copying (why Stack doesn't have collapsible sections ):</p>

<pre><code>&gt;&gt;&gt; from itertools import takewhile
from itertools import takewhile
&gt;&gt;&gt; g = [1,2,3,4,5]
&gt;&gt;&gt; [a for a in takewhile(lambda x: x &lt; 4, g)]
[1, 2, 3]
&gt;&gt;&gt; [g.pop() for _ in takewhile(lambda x: x &lt; 4, g)]
[5, 4, 3]
&gt;&gt;&gt; g = [1,2,3,4,5]
&gt;&gt;&gt; [g.pop(0) for _ in takewhile(lambda x: x &lt; 4, g)]
[1, 2]

&gt;&gt;&gt; g = ['1', '2', '3', '4', '5']
&gt;&gt;&gt; [a for a in takewhile(lambda x: x != '4', g)]
['1', '2', '3']
&gt;&gt;&gt; [g.pop() for _ in takewhile(lambda x: x != '4', g)]
['5', '4', '3']
&gt;&gt;&gt; g = ['1', '2', '3', '4', '5']
&gt;&gt;&gt; [g.pop(0) for _ in takewhile(lambda x: x != '4', g)]
['1', '2', '3']
</code></pre>

<p>I figured it out, because i've tried to use <code>deque</code> which raised <code>RuntimeError: deque mutated during iteration</code>.</p>

<p>Execution goes like this:</p>

<ol>
<li><code>g[0] = 1 &lt; 4; g.pop(0) =&gt; 1</code></li>
<li><code>g[1] = 3 &lt; 4; g.pop(0) =&gt; 2</code></li>
<li><code>g[2] = 5 &gt; 4; break</code></li>
</ol>

<p>This also explains why it worked in 2nd case, because during iteration <code>'4'</code> hasn't been hit.</p>

python python-2.7 list-comprehension pop