Confused with list assignment in Python

Viewed 44

I have the following code:

def proc1(p):
    p.append(1)
x=[2,5]
proc1(x)
print(x)


def proc2(p):
    p=p+[1]
y=[2,5]
proc2(y)
print(y)


z=[2,5]
z=z+[1]
print(z)

The output of the code is:

[2, 5, 1]
[2, 5]
[2, 5, 1]

I understand why the value of x and z have become [2,5,1]. But I don't understand why the value of y remains unchanged. I thought that after running proc2(y), y should have referred to [2,5,1].

My point is, I understand that y is not modified/mutated to [2,5,1]. But y is reassigned to a new list, which is [2,5,1], right? Then why does y still refer to the original value? If the value of z has changed, why not y?

I have checked the question What's the difference between plus and append in python for list manipulation, but I'm still confused.

0 Answers
Related