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

Deep copy Python with integers vs arrays

Given the following code:

x = y = z = 0
x = 10
print(y) // prints 0

x = y = z = [1, 2, 3, 4, 5]
x[0] = 10
print(y) // prints [10, 2, 3, 4, 5]

How come with simple integers Python does not perform a deep copy whilst with arrays it does?

question from:https://stackoverflow.com/questions/65891903/deep-copy-python-with-integers-vs-arrays

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

1 Reply

0 votes
by (71.8m points)

In the first example, you have three pointers pointing to a memory location for an integer. Then you direct one of the pointers, X, to a different memory location. The other two pointers continue to point to the original integer. In the second example, you have three pointers pointing to a list. The list is mutable. Then you change one of the items in the list. The three-pointers are still pointing to the same list and checking the value of any of them will return the same answer.


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

...