2

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.

failbetter
  • 143
  • 1
  • 9
  • @Grzegorz Oledzki, I checked the question that you think is a duplicate with my question. However, I think my question is a bit different from that question. What I don't understand is, if the value of z has changed, why not that of y? – failbetter Nov 24 '17 at 12:17
  • [Why does assigning to my global variables not work in Python?](https://stackoverflow.com/questions/929777/why-does-assigning-to-my-global-variables-not-work-in-python) – failbetter Nov 24 '17 at 12:40

0 Answers0