"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>I believe the problem is not with the <code>for</code> loop, but with the <code>print()</code> statement.</p>

<p>You cannot <code>+</code> a <code>string</code> with an <code>integer</code>, example:</p>

<p>This will not work:</p>

<pre><code>print("Hallo " + 4)
</code></pre>

<p>nor will this:</p>

<pre><code>print(4 + " Hallo")
</code></pre>

<p>if it is all integers it will work:</p>

<pre><code>print(4 + 1)
</code></pre>

<p>the error which is shown from <code>print("Hallo " + 4)</code> is "<code>builtins.TypeError: Can't convert 'int' object to str implicitly</code>"</p>

<p>The solution is to do the conversion from integer to string explicitely:</p>

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

<p>Now, for your question, I do not believe there is something as a "back log". The enumeration of <code>for x in lissi</code> is still valid, and <code>x</code> is still valid, just that while processing the first 4 enumerations (where <code>x</code> is a <code>string</code>) the <code>print()</code> statement will work, then it throws an error on the <code>print()</code> statement, but <code>x</code> is still a valid <code>integer</code>.</p>

python python-3.x for-loop memory