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

python - Does [:] slice only make shallow copy of a list?

I have experienced peculiar bugs from this [:] copy.

The docs say [:] makes only a shallow copy but seems:

a = [1,2,3]
id(a)
3071203276L
b=a[:]
id(b)
3071234156L

id(a) is not equal to id(b); how is that only a shallow copy?

Peculiar case:

import numpy as np
import random
a = np.array([1,2,3])
b=a[:]
random.shuffle(a)

b changes correspondingly.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Numpy answer:

Arrays in numpy are views/indexes on a backing storage.

You can copy the view, without copying the backing storage...

a=numpy.array([1,2,3,4])
b=a[:] # copy of the array ("view" or "index"), not the storage
b.shape=(2,2)
print a
# [1 2 3 4]
print b
# [[1 2]
#  [3 4]]
b *= 2
print a
# [2 4 6 8]
print b
# [[2 4]
#  [6 8]]

See how changing b affected a? Yet they still have a different shape. Consider them to be views of the data; and the b=a[:] line copied just this view. I could even modify the shape of b. Because it is just an index to the data, that says where columns and rows are located in memory.

If you want a copy of the backing storage in numpy, use a.copy().


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

...