Reference list object by a variable is different than for (some) other objects?

断了今生、忘了曾经 提交于 2019-12-08 12:53:05

问题


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


回答1:


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

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()

Your second case is just the same:

x = 5
y = x

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

x = 4




回答2:


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.



来源:https://stackoverflow.com/questions/44401453/reference-list-object-by-a-variable-is-different-than-for-some-other-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!