4

Suppose I have a function like this:

def f():
    x = np.arange(100)
    return x[:5]

f returns a y, which is a view on x.

Will x still be using memory in the background?

0

2 Answers 2

5

If you return a view x won't be garbage collected. Moreover it will be still accessible through base.

>>> y = f()
>>> y.base
array([ 0,  1,  2,  3,  4,  5,  6, ...., 99])
Sign up to request clarification or add additional context in comments.

Comments

5

Short answer: yes. Whilst x will be kept alive by your slice. See the documentation for basic slicing.

You should copy the view before returning.

return x[:5].copy() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.