1

What happens to the original numpy array when we slice it and set it to the same variable?

>>> a = np.arange(15).reshape([3,5])
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

>>> a = a[2:,:]
>>> a
array([[10, 11, 12, 13, 14]])

What happened to the original a array, was it garbage collected? However, we need the original array to refer to, so where is it stored?

3
  • 1
    Like any other python object, the array object itself will have one less reference. If this is the only reference to that object, the object is free to be garbage colllected. In CPython (which is pretty much assumed especially if you are using numpy) then it is reclaimed immediately when the ref count reaches 0. Note, the underlying buffer is not freed, since array-slices create views over the underlying buffer. Commented Sep 23, 2020 at 0:29
  • If you need the original array, why are you assigning the result to a again? Just b = a[2:, :] you have both the original and the outcome? Yes, if there are no further references to the original array, it will be garbage collected (in this case that means it will be around to provide the view - @juan.arrivillaga makes an important point). Commented Sep 23, 2020 at 0:30
  • yes, I was asking as a matter of curiosity. what do you mean by the underlying buffer? are the memory locations that are allocated by cpython still filled with the data then? For example, would the space in the RAM still be occupied? Commented Sep 24, 2020 at 1:49

1 Answer 1

2
In [69]: a=np.arange(15).reshape(3,5)

Arrays have a base attribute; in this case it references the 1d arange:

In [70]: a.base
Out[70]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])
In [71]: a = a[2:,:]
In [72]: a
Out[72]: array([[10, 11, 12, 13, 14]])

Same base. The (3,5) view is not available:

In [73]: a.base
Out[73]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])

But if the 2d array is a copy, not just a view:

In [74]: a=np.arange(15).reshape(3,5).copy()
In [75]: a.base
In [76]: a = a[2:,:]
In [77]: a.base
Out[77]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
Sign up to request clarification or add additional context in comments.

2 Comments

what does the copy have to do with storing the array in the base attribute? In line 75, why wouldn't we see any output?
a.base is None - it's not a derived array. It has its own data buffer (due to the copy).

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.