"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>The for loop is part of the scope it is declared in, so the following code will change the value of <code>x</code>:</p>

<pre><code>x = 9

for x in xrange(3): # iterate 0, 1, 2
    print(x)

print(x) # x == 2, x != 9
</code></pre>

<p>When the element was <code>"baz"</code>, everything was okay and the print statement worked. Python then continued execution. The next step was <code>x = 4</code>. After that, <code>print "Hallo" + x</code> failed with an error. </p>

<p>While running the interpreter, errors are caught and printed, then <em>execution continues</em>. There is no cleanup after an error in the interpreter, so the last value of <code>x</code> is still there when you check the value. This is why you see 4.</p>

python python-3.x for-loop memory