Reputation: 23
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.
Upvotes: 2
Views: 766
Reputation: 7996
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.
Upvotes: 1
Reputation: 168
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.
Upvotes: 3