python: loop a list of list and assign value inside the loop
<p>I have the following code, why the first one doesn't change <code>alist</code> while the second changes it?</p>

<pre><code>alist = [[1,2], [3,4], [5,6]]
for item in alist:
    item = 1
print(alist)

alist = [[1,2], [3,4], [5,6]]
for item in alist:
    item = item.append(10)
print(alist)
</code></pre>

<p>Referencing <a href="https://docs.python.org/3/reference/compound_stmts.html#the-for-statement" rel="nofollow">the document</a>: </p>

<blockquote>
  <p>The for-loop makes assignments to the variables(s) in the target list.
  This overwrites all previous assignments to those variables including
  those made in the suite of the for-loop:</p>

<pre><code>for i in range(10):
    print(i)
    i = 5             # this will not affect the for-loop
                      # because i will be overwritten with the next
                      # index in the range
</code></pre>
</blockquote>

<p>So your second example is identical to:</p>

<pre><code>alist = [[1,2], [3,4], [5,6]]
for item in alist:
    item.append(10)    # this statement modifies each item in alist
                       # , which is what item the variable "points to"
print(alist)
</code></pre>

<p>That is to say, <code>item</code> is a new variable <strong>in every iteration</strong>. As a result, assigning values to it in any specific iteration is pointless, because its value will be overridden by the reference to the next item in <code>alist</code> at the very beginning of the next iteration.</p>

python