0

In defining variable of a list object, for example:

x = [1,2,0.2,3,4]
y = x
x.sort()

I would expect that y is still equal to [1, 2, 0.2, 3, 4], but it does not. The value of y changed as x changed. To counter this, I found that using y = x.copy() can preserve the value in the first line.

On the other hand, another example :

x = 5
y = x
x = 4

from this the value of y is still 5, it does not change as x change.

My question : is this due to the design in list's class, or there is another explanation? I found the dynamic change also happen when using x.append(value). Any insight is appreciated. Regards, Arief

2

2 Answers 2

2

Every variable is just a pointer to an Python object, if you have two variables pointing to the same object then you'll see the changes in each of them (and .sort works in-place, if you want a new list you should use x = sorted(x)). However if you re-assign a variable then it will point to a different object.


I included some images to better visualize what's happening (not high-quality but I hope it conveys the message).

x = [1,2,0.2,3,4]
y = x

enter image description here

If you copy (it's a shallow copy so the list-contents still refer to the same items!):

x = [1,2,0.2,3,4]
y = x.copy()

enter image description here

Your second case is just the same:

x = 5
y = x

enter image description here

But then you re-assign the variable x (so it points to another object thereafter):

x = 4

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the insight and answer. So it is not like if x = [1, 2, 3], then x has value [1, 2, 3]. But, from what I understand, it simply means the list object [1, 2, 3] can being called by x. If a variable refer to another variable : y = x, then it can be perceived as passing reference two times, calling y is as same as calling x and then calling the existing object [1, 2, 3]. They depend on the same object. Regards.
0

The problem is, y and x are just references to the class list.

When you do something like:

y=x

You are coping the reference of the class and not creating another one.

When using copy you are doing a shallow copy that are creating a new class, copying all elements again to this new object.

Python manual presents a explanation and others operators used to actually copy a full class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.