+ 3

Why y does not change?

x=[1,2,3,4,5] y=x x=x+[3] print(y) #output=[1,2,3,4,5] but output should be [1,2,3,4,5,3] because x is change.can anyone explain this.

17th May 2018, 4:23 PM
Maninder $ingh
Maninder $ingh - avatar
7 ответов
+ 3
I find it. y depend upon first x only but y does not depend upon 2nd x.so we change only 2nd x which has no effect on y variable. Because id(x)!=id(y)
17th May 2018, 4:36 PM
Maninder $ingh
Maninder $ingh - avatar
+ 3
Mirko Schultz I'm also still learning. This is just one of those things in Python. What Python does when you say x=y its like it creates a tag with y written on it that it attaches to the basket that contains the contents of x. ( the basket now has 2 lables x and y). So when you change the items in the basket labled y, that same basket also has the lable x. So x also changes. But when you say x=x+[9] it creates a new basket that is a copy of the old and adds 9 to it, takes the x lable off the old basket attaches it to the new basket.
18th May 2018, 5:52 PM
Louis
Louis - avatar
17th May 2018, 5:47 PM
Louis
Louis - avatar
+ 1
Louis So setting x=y means both point to the exact same list, like references/pointers in other languages (I use(d) C++, Java & C# for many many years). I was just surprised because adding a number at the end really creates a new list instead of just adding a number. Thanks for your help.
18th May 2018, 7:05 PM
Mirko Schultz
Mirko Schultz - avatar
18th May 2018, 8:02 PM
Louis
Louis - avatar
0
You are setting y to x. x is [1,2,3,4,5]. Then you are changing x after you set y. So y is still [1,2,3,4,5] but now x is [1,2,3,4,5,3]. You need to move y under x=x+3. It should look like this: x=[1,2,3,4,5] x=x+[3] y=x
17th May 2018, 4:36 PM
Xpl0it
Xpl0it - avatar
0
Louis, I am new to Python and have a question about your program. When you set y to x they point to the same list, when y [1] changes it affects y and x but when y gets a new number at the end y becomes a new list so x and y are different lists. Is that right?
18th May 2018, 5:19 AM
Mirko Schultz
Mirko Schultz - avatar