0

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?

2 Answers 2

4
mylist * 2

is equivalent to

mylist + mylist #resulting list has 2 references to each element in mylist 
                #stored as:
                #[mylist[0],mylist[1],...,mylist[0],mylist[1],...]
                #   ^ ----------------------^
                #   reference the same object

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:

lst_of_arrays = [ np.zeros(1) for _ in range(N) ]

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):

X,Y = ( np.zeros(1) for _ in range(2) )
X,Y,Z = ( np.zeros(1) for _ in range(3) )
W,X,Y,Z = ( np.zeros(1) for _ in range(4) )
...

(and, in anticipation of an otherwise inevitable comment, in python2.x, you can use xrange instead of range to save the overhead of creating a list ...)

Sign up to request clarification or add additional context in comments.

2 Comments

What's the point of saving the overhead of creating a list in code that creates a list?
@ecatmur, are you talking about my aside about xrange? If you use range in python2.x, you create 2 lists (range creates an additional list which is iterated over in the list-comp/generator) instead of just creating 1 (the one you want).
3

Another solution without using a list comprehension or generator would be:

X, Y = np.zeros((2,1))

So if you need e.g. three arrays of shape (5, 5) it would be:

X, Y, Z = np.zeros((3, 5, 5))

For a good explanation of what went wrong in the original example I refer to mgilson's answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.