2

... but changing the values of the numpy array works:

import numpy as np

def reshapeArray(arr):
    arr = arr.reshape((2, 2))
    arr /= 10
    print(arr) # prints [[0.1 0.3], [0.2 0.4]]

arr = np.array([1, 2, 3, 4], dtype=np.float32)
reshapeArray(arr)
print(arr) # prints [0.1 0.2 0.3 0.4]

The reshapeArray() function changed values of the array permanently, but changed the shape of the array temporarily. If I add a return line (return arr) to end of the function, and assign the output of the function to the array (arr = reshapeArray(arr)), this time it works. But I wonder why it didn't work without returning the array?

2 Answers 2

3

From the docs (numpy.reshape):

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

As opposed to arr = arr / 10, which does makes a copy and reassigns it.

Apparently a view is lost when leaving scope...

Sign up to request clarification or add additional context in comments.

1 Comment

The arr=... breaks the back reference. That's basic python function variable scoping. The view is a new object.
0

Try to return an array from function and assign the returned value to the desired variable:

    return arr  # The last string of your function

arr = reshapeArray(arr)

1 Comment

Note that OP explicitly said that's something they've tried (and know that it works) but would like to know why this works.

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.