Reputation: 677
def foo():
x = np.ones((10,10))
return x[:5,:5]
If I call y = foo()
I'll get a 5x5 array (1/4 of the values in x
). But what happens to the other values in x
, do they persist in memory or get garbage collected in some way? I'd like to understand this.
Upvotes: 5
Views: 850
Reputation: 280426
As kindall says in the comments, basic slicing on a NumPy array creates a view of the original array. The view has to keep the entire original object alive; you can see the reference it uses to do so in the view's base
attribute.
In [2]: x = numpy.ones((10, 10))
In [3]: y = x[:5, :5]
In [4]: y.base is x
Out[4]: True
Upvotes: 3