Tony Chen Tony Chen - 3 months ago 9
Python Question

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?

It's the similar question with this one I asked (Visit How can python function actually change the parameter rather than the formal parameter? ), 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:

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)


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
twomerger
. 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
[0, 2, 4, 4]
and
[2, 2, 4, 4]
which means the function doesn't work. So I am confused again.

Answer

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

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)

Output:

[0, 4, 8, 8]
[2, 0, 0, 0]

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

def twomerger(lx, ly):
    for i, num in enumerate(lx):
        if lx[i] == ly[i]:
            lx[i] += ly[i]
            ly[i] = 0

Or if you're comfortable with zip:

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