简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM