1

I noticed that the augmented addition assignment operator (+=) behaves in an unexpected way within functions. See below:

import numpy as np

def f(array):
    array += 1
    return array

x = np.ones(5)

print(x)

y = f(x)

print(x)

This outputs:

[ 1.  1.  1.  1.  1.]
[ 2.  2.  2.  2.  2.]

So the array x is being modified within the function. Can anyone explain this? If instead of x += 1 I use x = x + 1, then the behavior is as expected (i.e. changes within the function do not affect the array x outside it.)

Obviously this is not causing my any problems (any more) - the solution is easy. Just looking to understand why this is happening.

Thanks!

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    [Closely related](https://stackoverflow.com/questions/2347265/why-does-behave-unexpectedly-on-lists). Numpy seems to be basing the behavior on the behavior of lists. Compound operators like `+=` and `*=` are generally mutative on collections. – Carcigenicate Nov 14 '19 at 21:38
  • Exactly: one, the increment operator, mutates the array in-place. The other one, the assignment, creates a new name and array – Pynchia Nov 14 '19 at 21:47
  • 1
    Possible duplicate of [Why does python/numpy's += mutate the original array?](https://stackoverflow.com/questions/35910577/why-do-python-numpy-mutate-the-original-array) – Carcigenicate Nov 14 '19 at 21:48
  • This really has nothing to do with being inside versus outside a function. Rather, the augmented assignment operators should behave in-place (i.e. they are mutator methods) where the collection is mutable. So, this won't happen with `str` objects, but it will with `list` objects. Of course, you can implement then to *not* work this way, but that is what the data model says they should do. – juanpa.arrivillaga Nov 14 '19 at 21:57
  • 1
    It doesn't necessarily have "global" implications. The `+=` assignment changes the object referenced on the left-hand side in-place. In this case that just happens to be the global variable that was passed to the function. – martineau Nov 14 '19 at 21:57
  • Not sure if I'm allowed to ask for clarification on a closed question, but I'm going to try. I am surprised that my original array can be modified within the function. I don't know how to frame that as a question, but anything you can say to help me make sense of that would be appreciated. If you even see this... – user2577043 Nov 14 '19 at 22:52
  • The variable `x` references an array object. When used in `f(x)`, that reference (or it you prefer, that array object) is passed into the function. So until you do something like `array = ...`, `array` within the function references the same object as `x` outside. If you `id(x)`, `id(array)` and `id(y)`, you'll see the id number. – hpaulj Nov 15 '19 at 00:08

0 Answers0