Fully understand for loop python
<p>I start out with a small code example right away:</p>

<pre><code>def foo():
    return 0

a = [1, 2, 3]

for el in a:
    el = foo()

print(a) # [1, 2, 3]
</code></pre>

<p>I would like to know what <strong><em>el</em></strong> is in this case. As <strong><em>a</em></strong> remains the same, I intuite that <strong><em>el</em></strong> is a reference to an int. But after reassigning it, el points to a new int object that has nothing to do with the list <strong><em>a</em></strong> anymore.</p>

<p>Please tell me, if I understand it correctly. Furthermore, how do you get around this pythonic-ly? is <em>enumerate()</em> the right call as</p>

<pre><code>for i, el in enumerate(a):
    a[i] = foo()
</code></pre>

<p>works fine.</p>

<p>Yes, you understood this correctly. <code>for</code> sets the target variable <code>el</code> to point to each of the elements in <code>a</code>. <code>el = foo()</code> indeed then updates that name to point to a different, unrelated integer.</p>

<p>Using <code>enumerate()</code> is a good way to replace the references in <code>a</code> instead.</p>

<p>In this context, you may find the <a href="http://nedbatchelder.com/text/names.html" rel="nofollow"><em>Facts and myths about Python names and values</em> article</a> by Ned Batchelder helpful.</p>

<p>Another way would be to create a new list object altogether and re-bind <code>a</code> to point to that list. You could build such a list with a list comprehension:</p>

<pre><code>a = [foo() for el in a]
</code></pre>

python python-3.x for-loop reference