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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With