2

I try to replace the value of the first element with the value of the second element on a numpy array and a list whose elements are exactly the same, but the result I get is different.

1) test on a numpy array:

test=np.array([2,1])
left=test[:1]
right=test[1:]
test[0]=right[0]
print('left=:',left)

I get: left=: [1]

2) test on a python list:

 test=[2,1]
 left=test[:1]
 right=test[1:]
 test[0]=right[0]
 print('left=:',left)

I get: left=: [2]

Could anyone explain why the results are different? Thanks in advance.

2
  • Please reformat code block for readability. Use code block icon in formatter, or back quotes. Commented May 17, 2019 at 16:35
  • @kcw78, thanks for your suggestion. This is the first time I post a question on stack overflow so I don't know much about the format issue. I have revised the format of the code and hope it is easier to read now. Commented May 18, 2019 at 20:10

2 Answers 2

3

Slicing (indexing with colons) a numpy array returns a view into the numpy array so when you later update the value of test[0] it updates the value of left as left is just a view into the array.

When you slice into a python list it just returns a copy so when you update the value of test[0], the value of left doesn't change.

This is done because numpy arrays are often very large and creating lots of copies of arrays could be quite taxing.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, James. Now I understand it.
1

To expand on James Down explanation of numpy arrays, you can use .copy() if you really want a COPY and not a VIEW of your array slice. However, when you make a copy, you would have to do the copy of left again after reassigning test[0]=right[0] to get the new value.

Also, regarding the list method, you set test[0]=right[0], so if you print (list) after the assignment, you will get [1 1] instead of the original [2, 1]. As James pointed out, left is a copy of the list item, so not updated with the change to the list.

1 Comment

Thanks @kcw78. I came across this problem when I tried to implement the merge sort algorithm on a numpy array and it didn't work. But when I tried to add .copy() when slicing the list it worked. So I thought about the root of the problem. Actually I read in the book 'Python for data analysis' that the slice of a numpy array is just a view of it, but I don't really understand it until James and you pointed it out for me. Thank you all again.

Your Answer

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.