"Backlog" of a loop through a list in Python
<p>I have a weird Python beginner's question,.. playing around in my virtual env in the interpreter (python 3.5):</p>

<p>I have a list with mixed types: </p>

<pre><code>lissi = ["foo", "bar". "boo", "baz", 4, 7]
</code></pre>

<p>And then "accidentally" try to print out all elements in a <strong>for loop</strong> concatenated to a string:</p>

<pre><code>for x in lissi:
   print("Hallo " + x)
</code></pre>

<p>This, of course, is not possible bcs. we cannot conc. integers to a String - so the first elements are printed and then there is a TypeError. </p>

<p>Then I typed just <code>"x" and enter</code> to see if there is still data stored and yes it is: <strong>x is 4</strong>. </p>

<p><code>type(x)</code> is <code>int</code> (tried that to figure out if 7 is also still there).</p>

<p>So my question is: What happens "under the hood" in Python in the for loop: Seems as if every successfully processed element is removed, but there is a backlog stored in x which is the first element the TypeError was thrown for? And is there a way to "clear" this data from memory in case of errors? </p>

<p>thx</p>

<p>It's not a backlog and nothing like "every successfully processed element is removed".<br>
Basically on every iteration <code>for</code> loop assigns to variable <code>x</code> the value of next element of list <code>lissi</code> (doesn't have to be a list, can be any iterable).<br>
Whenever the loop breaks, due to exception or <code>break</code> statement, variable <code>x</code> is left intact, so it contains the last value assigned by the <code>for</code> loop.<br>
This is ok, since loops don't have any isolated scope in Python and actually makes it convenient to search iterable for interesting element, breaking the loop when it's found and not being forced to store it in another variable before leaving the loop. </p>

python python-3.x for-loop memory