1

If I add an array to another, Numpy appears to be making a copy of the original array:

>>> a = np.array([2,3])
...: b = a
...: a = a+np.array([1,1])
...: print a, b
[3 4] [2 3]

In contrast, if I use the += idiom, the original array appears to be changed in place.

>>> a = np.array([2,3])
...: b = a
...: a += np.array([1,1])
...: print a, b
[3 4] [3 4]

What is happening here? When are arrays changed in-place and when are they automatically copied?

dkv
  • 6,602
  • 10
  • 34
  • 54
  • 2
    In general `x += y` is not equivalent to `x = x + y`. The former is defined by whatever the object's type defines for `__iadd__` and the latter by however the type defines `__add__`. The *convention* is that if the type is mutable, `__iadd__` should work *in-place*. So, for example, with a `list` object, `+=` will modify the list in-place, but for `tuple` objects or `int` objects, which are immutable, new objects will be created and assigned to `x` – juanpa.arrivillaga Dec 26 '18 at 19:56
  • @Juana.arrivillaga it's surely worth noting that this holds for python, and is not numpy-specific, where copies may have to be made implicitly – roganjosh Dec 26 '18 at 19:59
  • 1
    @roganjosh yes, indeed, in my examples, I never mention `numpy` objects, but just to be explicit, this is for *any* Python object. And for user-defined objects, really, `__iadd__` and `__add__` will have behavior defined by the *user* and could really do anything. – juanpa.arrivillaga Dec 26 '18 at 20:10

0 Answers0