Issue
In numpy if we have a nD array and then we have multiple slices of the same nD array then if we make change in one of them then it's gonna reflect in all slices[i.e. no new object is created] Then why if we check the id() of these slices then they appear different?
Ex::
import numpy as np
a = np.array([10,20,30,40,50,60,70,80,90])
b = a[:5]
c = a[2:6]
d = a[3:7]
a
array([10, 20, 30, 40, 50, 60, 70, 80, 90])
b
array([10, 20, 30, 40, 50])
c
array([30, 40, 50, 60])
d
array([40, 50, 60, 70])
a[3]=9999
a
array([ 10, 20, 30, 9999, 50, 60, 70, 80, 90])
b
array([ 10, 20, 30, 9999, 50])
c
array([ 30, 9999, 50, 60])
d
array([9999, 50, 60, 70])
id(a)
1592350341040
id(b)
1592350341424
id(c)
1592353526704
id(d)
1592750164944
.
Solution
This is because slices can also be thought of as "views". They are all different views into the same actual memory on your computer.
So, if you change the content of that memory via one view, the other views will reflect that change.
However, they are different views, and hence they have different results for id
.
Answered By - cadolphs
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.