0

From the code below, why doesn't the list (z) retain it's value before appending another numpy array (r) to it? (after z becomes non-empty, z seems to get r value even before appending r to it) How do you make it retain value? For example, the end result should be z =

[[0. 0. 1.]
 [0. 0. 2.]
 [0. 0. 3.]
 [0. 0. 4.]
 [0. 0. 5.]]

code:

    import numpy as np
    r = np.zeros(3)
    z=[]
    for i in range (1,6):
      r[2] = i
      print("r")
      print(r)
      print("z before appending r")
      print(z)
      z.append(r)
      print("z after appending r")
      print(z)
    z=np.array(z)
    print("z after numpy'd")
    print(z)

run result:

r
[0. 0. 1.]
z before appending r
[]
z after appending r
[array([0., 0., 1.])]
r
[0. 0. 2.]
z before appending r
[array([0., 0., 2.])]
z after appending r
[array([0., 0., 2.]), array([0., 0., 2.])]
r
[0. 0. 3.]
z before appending r
[array([0., 0., 3.]), array([0., 0., 3.])]
z after appending r
[array([0., 0., 3.]), array([0., 0., 3.]), array([0., 0., 3.])]
r
[0. 0. 4.]
z before appending r
[array([0., 0., 4.]), array([0., 0., 4.]), array([0., 0., 4.])]
z after appending r
[array([0., 0., 4.]), array([0., 0., 4.]), array([0., 0., 4.]), array([0., 0., 4.])]
r
[0. 0. 5.]
z before appending r
[array([0., 0., 5.]), array([0., 0., 5.]), array([0., 0., 5.]), array([0., 0., 5.])]
z after appending r
[array([0., 0., 5.]), array([0., 0., 5.]), array([0., 0., 5.]), array([0., 0., 5.]), array([0., 0., 5.])]
z after numpy'd
[[0. 0. 5.]
 [0. 0. 5.]
 [0. 0. 5.]
 [0. 0. 5.]
 [0. 0. 5.]]
pg405
  • 65
  • 6

2 Answers2

1

Reason is z.append(r) add the same object which is pointed by r into z, so z is a list of five same objects in the end.

Change that statement to z.append(np.array(r)) and have another try.

Yang Liu
  • 346
  • 1
  • 6
  • Thank you! That works!! In python, do I pretty much assume when passing anything other than immutable, it will be passed by reference? Since np.array is mutable, why does it work/fix the problem in this case? – pg405 Jan 23 '21 at 21:56
  • You welcome. That works as `z.append(np.array(r))` raises a new object which is initialized using `r`, and adds this new object into `z`. For **by reference**, maybe you would like to have a look on following page - https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference – Yang Liu Jan 25 '21 at 01:04
0

You are appending a new row at each iteration, accordingly you should do z[i-1, 2] = i

Tarik
  • 10,810
  • 2
  • 26
  • 40