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
782 views
in Technique[技术] by (71.8m points)

python: mutating the copy of a list changes the original?

So until now, i was under the assumption that if you have for example:

L = [1,2,3]
L2 = L1
L2.append(5)

both L and L2 would be affected by the append code.

however, when you assign L2 to be a copy of a list, for example:

L = [1,2,3]
L2 = L[:]
L2.append(5)

only L2 would be affected, and L still refers to [1,2,3]

but i now run into this:

x = [1, 2]
L1 = [x, [8, 9]]
L2 = L1[:]
L2[0][1] = 999

>>>print(L1)
[[1,999],[8,9]]
>>>print(L2)
[[1,999],[8,9]]

why was it that in this case, both lists changed?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Slicing is a shallow copy. A copy created by slicing will contain new references to the old elements of the original list; if the original list contained mutable objects such as more lists, the copy will contain references to those same lists. You can use copy.deepcopy to try to get around this, or loop through your original list and slice-copy the elements into a new list. Be careful with copy.deepcopy, though; there's often some depth at which you want to stop making copies and keep the original elements.


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

...