2

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]
Peter Haddad
81.2k26 gold badges148 silver badges149 bronze badges
asked Jul 17, 2017 at 16:19

1 Answer 1

3

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.

answered Jul 17, 2017 at 16:24
Sign up to request clarification or add additional context in comments.

3 Comments

np.array takes a copy parameter, which by default is True.
@hpaulj good point. I'll add the information to the question.
Thanks for the response. I understand now. You have been a great help.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.