0

What's going on here? I'm sure there's a simple solution/fact I'm overlooking. I just can't understand why I can't save values/changes to a NumPy array in this manner.

>>> import numpy as np
>>> memoize = []
>>> parameters = np.array([1, 2]).astype(np.float64)
>>> memoize.append(parameters)
>>> parameters -= np.array([0.5, -0.5])
>>> memoize.append(parameters)
>>> memoize
[array([ 0.5,  2.5]), array([ 0.5,  2.5])]

I expected the answer to be

[array([ 1.,  2.]), array([ 0.5,  2.5])]

Does it have anything to do with a list being mutable ?

bjd2385
  • 2,013
  • 4
  • 26
  • 47
  • No, it's because you keep appending *the same array*. So you have a list of references to the same array, which is why changes to that array are reflected at every point in the list. Indeed, the problem is that `list.append` **is** reflecting the variable changes! – juanpa.arrivillaga Apr 11 '17 at 19:21
  • @juanpa.arrivillaga man that's tricky. Yes, I see it's updating both elements. Totally unexpected. – bjd2385 Apr 11 '17 at 19:22
  • I mean, this is how *everything* in Python works. It's pretty obvious, you are doing `memoize.append(parameters)` over and over again... – juanpa.arrivillaga Apr 11 '17 at 19:23
  • So, try this `mylist = []; x = []`, then `mylist.append(x); mylist.append(x)`. Now `print(mylist)`, then `x.append(42)`, and now try `print(mylist)` – juanpa.arrivillaga Apr 11 '17 at 19:25
  • Anyway, read and understand [this](https://nedbatchelder.com/text/names.html) article by SO legend, Ned Batchelder. I think then it will become obvious. – juanpa.arrivillaga Apr 11 '17 at 19:26
  • I hardly think that's obvious. But thank you for the link, looks like an interesting read. – bjd2385 Apr 11 '17 at 19:28
  • 2
    Possible duplicate of [Python list problem](http://stackoverflow.com/questions/1959744/python-list-problem) – Stephen Rauch Apr 11 '17 at 19:40

1 Answers1

1

The issue you're having is that parameters is a mutable value, and you're appending multiple references to it while mutating it in place. If you rebound the variable to a new array each time, you wouldn't have an issue.

Try changing

parameters -= np.array([0.5, -0.5])

to

parameters = parameters - np.array([0.5, -0.5])

The original version makes an in-place modification to parameters. The second version makes a new array with copied data. This is probably a little slower, but it does what you want in this situation.

Blckknght
  • 100,903
  • 11
  • 120
  • 169