0
How is assignment of mutable elements done in Python
I am new to python. Please go through below code and help me out with my questions present in comments https://code.sololearn.com/cVo9T314LcwC/?ref=app
2 Respuestas
+ 2
x =[1,2,3] // store in x the reference (mrmory adresse of the array [1,2,3]
y = x // copy the reference from x in y
# case 1
x += [4] // concat array [4] to array referenced by x (and so by y, as x == y)
print(x)
print(y)
#in above output both x and y are equal
// and that's what's expected ^^
x=x +[5] // first create a new array (at another memory location) by concatenating x and [5] (but without modifying the original array), then assign to x the reference to the new array (while y keep the original array reference, so y != x)
print(x)
print(y)
#in above output x and y are different. Why there is difference? code x+= and x= x+ are both same right ?
// TL;TR
// in the first case, it's implicit that you modify the array in place, while in the other you explivitly do the oprration on a brand new object (array).
0
Thank you visph . I get it now.