I want to create multiple matrices with numpy.zeros((N,M)). But I just realized that this not working as I though it would:
can someone explain me the outcome of the following code (1dim arrays for simplicity):
#!/usr/bin/python
import numpy as np
#sequential array creation
X=np.zeros(1)
Y=np.zeros(1)
X[0],Y[0]=1.0,2.0
print X,Y
#multiple array creation
X,Y=[np.zeros(1)]*2
X[0],Y[0]=1.0,2.0
print X,Y
the result is
[ 1.] [ 2.]
[ 2.] [ 2.]
this means the second method to create the arrays does not work…
What is the prober way to create many ndarrays with identical dimensions in 1 line?
is equivalent to
So in your case, you’re making a numpy array, and then you’re putting it in a list. When you multiply that list, the resulting list has 2 references to the same array.
If you want to create multiple arrays and put them in a list, a list comprehension will do just fine:
Or if there are few enough of them to unpack, you can use a generator or a list-comprehension (below I opt for the generator):
(and, in anticipation of an otherwise inevitable comment, in python2.x, you can use
xrangeinstead ofrangeto save the overhead of creating a list …)