How to create multiple arrays at one time

Viewed 386
a = np.zeros(100)
b = np.zeros(100)
c = np.zeros(100)

is urgly.

However,

a,b,c = np.zeros(100) 

doesn't work.

6 Answers

You can use list comprehension:

a,b,c = [np.zeros(100) for i in range(3)]

If you know that a,b,c have roughly the same life time, then

a,b,c = np.zeros((3,100))

is a good and fast solution, otherwise it's a memory leak.

Always works:

a,b,c = (np.zeros(100) for _ in "abc")

Note that _ being a dummy iterating over a string is no less meaningful (and faster) than using range(3).

Similarly, for just three terms

a,b,c = [np.zeros(100) for _ in "abc"]

is actually slightly faster than the generator expression.

Even faster:

a,b,c = map(np.zeros,3*(100,))

This is not a valid statement since you are trying to assign a single array object to the three different objects:

a,b,c = np.zeros(100) 

Other than list comprehension, you can also use the following:

a,b,c = np.zeros(100), np.zeros(100), np.zeros(100)

Edit: You can also just use a,b,c = np.zeros((3,100)) as mentioned by @hpaulj

If you don't mind a, b and c being the same array, you can also do it this way:

a, b, c = [np.zeros(100)] * 3

which is reasonably succinct. Otherwise, you can try @marc-dillar's method using a list comprehension instead.

Try this (pure numpy):

a,b,c = np.zeros((3,100))
a = b = c = np.zeros(100)

assigns the same array to 3 variables

a,b,c = np.zeros((3,100))

This unpacking performs an iteration on the RHS, effectively

a,b,c = list(np.zeros((3,100))
a,b,c = [row for row in np.zeros((3,100))]

These will all be views of the original RHS. Instead of assigning to 3 variables, you could work with

abc = np.zeros((3,100))

But it's hard to choose among the alternatives without knowing how you will use them. These are just a stepping stone toward creating more useful arrays.

In [285]: abc = np.zeros((3,10),int)
In [286]: abc[0,:] = 1
In [287]: abc[1,:] = np.arange(10)
In [288]: abc[2,:] = np.random.randint(0,10,10)
In [289]: abc
Out[289]: 
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [4, 2, 9, 9, 4, 3, 1, 0, 0, 5]])

   
Related