Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

python - Changing list elements in shallow copy

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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

enter image description here

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:

enter image description here

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...