Why I use list as a parameter of a function and the function can't change the value of the actual parameter but only the formal parameter?
<p>It's the similar question with this one I asked (Visit <a href="http://stackoverflow.com/questions/39160682/how-can-python-function-actually-change-the-parameter-rather-than-the-formal-par?noredirect=1#comment65665408_39160682">How can python function actually change the parameter rather than the formal parameter?</a> ), Only this time I am using list to be formal parameter. So because list is reference type? It should worked as before.
So here is my code:</p>

<pre><code>def twomerger(lx, ly):
    if lx[0] == ly[0]:
        lx[0] = ly[0]
        ly[0] = 0
    if lx[1] == ly[1]:
        lx[1] = ly[1]
        ly[1] = 0
    if lx[2] == ly[2]:
        lx[2] = ly[2]
        ly[2] = 0
    if lx[3] == ly[3]:
        lx[3] = ly[3]
        ly[3] = 0


row1 = [0, 2, 4, 4]
row2 = [2, 2, 4, 4]
twomerger(row1, row2)
print (row1)
print (row2)
print ("it's a new situation:")
print (row1)
print (row2)
</code></pre>

<p>Here I try to transfer [0, 2, 4, 4] and [2, 2, 4, 4] into [0, 4, 8, 8] and [2, 0, 0, 0]. (make the same vertical number adds up). I passed two list -- row1 and row2 into the parameter of my function <code>twomerger</code>. I thought because row1 and row2 is list, they are reference so this function should be able to change the row1 and row2. However it gives me the result <code>[0, 2, 4, 4]</code> and <code>[2, 2, 4, 4]</code> which means the function doesn't work. So I am confused again. </p>

<p>I think your issue is that you should be adding to the values in the list, but instead you're reassigning. Change <code>=</code> to <code>+=</code>:</p>

<pre><code>def twomerger(lx, ly):
    if lx[0] == ly[0]:
        lx[0] += ly[0]
        ly[0] = 0
    if lx[1] == ly[1]:
        lx[1] += ly[1]
        ly[1] = 0
    if lx[2] == ly[2]:
        lx[2] += ly[2]
        ly[2] = 0
    if lx[3] == ly[3]:
        lx[3] += ly[3]
        ly[3] = 0

row1 = [0, 2, 4, 4]
row2 = [2, 2, 4, 4]
twomerger(row1, row2)
print (row1)
print (row2)
</code></pre>

<p><strong>Output</strong>:</p>

<pre><code>[0, 4, 8, 8]
[2, 0, 0, 0]
</code></pre>

<p>For what it's worth, your method can be written much more concisely:</p>

<pre><code>def twomerger(lx, ly):
    for i, num in enumerate(lx):
        if lx[i] == ly[i]:
            lx[i] += ly[i]
            ly[i] = 0
</code></pre>

<p>Or if you're comfortable with <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip</code></a>:</p>

<pre><code>def twomerger(lx, ly):
    for i, (a, b) in enumerate(zip(lx, ly)):
        if a == b:
            lx[i] += b
            ly[i] = 0
</code></pre>

python function python-3.x