Changing list elements in shallow copy

时间秒杀一切 提交于 2019-11-30 09:08:28

问题


I have one question about list shallow copy.

In both examples, I modified one element of the list, but in example 1, list b changed, while in example 2, list d is not changed. I am confused since in both examples, I modified an element of the list.

What's the difference?

Example 1:

a=[1,2,[3,5],4]
b=list(a)
a[1]=0
print(a)   # [1, 0, [3, 5], 4]
print(b)   # [1, 2, [3, 5], 4]

Example 2:

c=[1,2,[3,5],4]
d=list(c)
c[2][0]=0
print(c)   # [1, 2, [0, 5], 4]
print(d)   # [1, 2, [0, 5], 4]

回答1:


A shallow copy means that you get a new list but the elements are the same. So both lists have the same first element, second element, etc.

If you add, remove, or replace a value from the shallow copied list that change is not reflected in the original (and vise-versa) because the shallow copy created a new list. However if you change an element in either that change is visible in both because both lists reference the same item. So the inner list is actually shared between both the new list and the old list and if you change it, that change is visible in both.

Note that you actually didn't change an element in either example, you replace an element of the list in the first example and in the second example, you replace an element of an element of your list.

I'm currently using graphviz a lot so let me add some images to illustrate this:

The shallow copy means you get a new list but the objects stored in the list are the same:

If you replace an element in any of these the corresponding element will just reference a new item (your first example). See how one list references the two and the other the zero:

While a change to an referenced item will change that item and every object that references that item will see the change:




回答2:


In the both examples, you are creating a shallow copy of the list. The shallow copies essentially copies the aliases to all elements in the first list to the second list.

So you have copied the reference to an [int, int, list, int]. The int elements are immutable, but the list element is mutable. So the third elements both point to the same object in Python's memory. Modifying that object modifies all references to it.



来源:https://stackoverflow.com/questions/48178836/changing-list-elements-in-shallow-copy

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