2021-12-26

Numpy array indexing: view or copy - depends on scope?

Consider the following array manipulations:

import numpy as np
def f(x):
     x += 1
x = np.zeros(1)
f(x)       # changes `x`
f(x[0])    # doesn't change `x`
x[0] += 1  # changes `x`

Why does x[0] behave differently depending on whether += 1 happens inside or outside the function f?

Can I pass a part of the array to the function, such that the function modifies the original array?


Edit: If we considered = instead of +=, it seems that we would maintain the core of the question while getting rid of some irrelevant complexity.



from Recent Questions - Stack Overflow https://ift.tt/3H6HyP2
https://ift.tt/eA8V8J

No comments:

Post a Comment