I'm confused as to why the following two print(an_array) statements gives two different results.
Although b_slice is explicitly defined as a np.array during
assignment,both a_slice and b_slice are of the same type using type command.Yet a-slice will change the value of an_array while b_slice will not. If someone could point me to the explanation I would greatly appreciate it.
an_array = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
a_slice = an_array[:2, 1:3]
print(type(a_slice)) # <class 'numpy.ndarray'>
print(type(b_slice)) # <class 'numpy.ndarray'>
b_slice = np.array(an_array[:2, 1:3]
b_slice[0,0] = 2000
print(an_array) # returns no change to an_array
[[1 2 3 4]
[5 6 7 8]
[9 10 11 12]]
a_slice[0,0] = 2000
print(an_array) # shows the change from the number 2 to the number 2000
[[1 2000 3 4]
[5 6 7 8]
[9 10 11 12]
1 Answer 1
Because you explicitly* make a copy by calling the np.array constructor:
b_slice = np.array(an_array[:2, 1:3])
Whereas:
a_slice = an_array[:2, 1:3]
Is the result of a slice, which in numpy create views instead of shallow copies, unlike vanilla lists.
Note * as @hpaulj points out, the np.array constructor takes a copy argument, which defaults to True.
3 Comments
np.array takes a copy parameter, which by default is True.