 Tony Chen -4 years ago 126
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 == ly:
lx = ly
ly = 0
if lx == ly:
lx = ly
ly = 0
if lx == ly:
lx = ly
ly = 0
if lx == ly:
lx = ly
ly = 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. Karin
Answer Source

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 == ly:
lx += ly
ly = 0
if lx == ly:
lx += ly
ly = 0
if lx == ly:
lx += ly
ly = 0
if lx == ly:
lx += ly
ly = 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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
Latest added