1

I am trying to initialize a list of numpy arrays in the following way

import numpy as np
sol=[np.zeros(5)]*4

But when I try to modify one of the list members like this,

sol[0][2:4]=[1,1]

It changes all the list members instead of only the first one

[array([ 0.,  0.,  1.,  1.,  0.]), array([ 0.,  0.,  1.,  1.,  0.]), array([ 0.,  0.,  1.,  1.,  0.]), array([ 0.,  0.,  1.,  1.,  0.])]

I guess it is old story about mutable and inmutable objects, but I simply don't know how to solve it.

I tried using copy and deepcopy, but not successful.

Sorry if it is duplicated entry, but I couldn't find any similar question

Thanks

manolius
  • 395
  • 3
  • 15

1 Answers1

2

and the answer is:

np.zeros((4, 5))

and to explain the point about mutable objects. when you do this:

[np.zeros(5)] * 4

it's functionally the equivalent of this:

a = np.zeros(5)
[a, a, a, a]
acushner
  • 9,595
  • 1
  • 34
  • 34