Search code examples
pythonarraysnumpymultiplication

Save result of multiplication to existing array


Consider the following code:

a = numpy.array([1,2,3,4])
b = numpy.array([5,6,7,8])
# here a new array (b*2) will be created and name 'a' will be assigned to it
a = b * 2 

So, can numpy write the result of b*2 directly to memory already allocated for a, without allocating a new array?


Solution

  • Yes this is possible - you need to use np.multiply with its out parameter:

    np.multiply(b, 2, out=a)
    

    The array a is now filled with the result of b * 2 (and no new memory was allocated to hold the output of the function).

    All of NumPy's ufuncs have the out parameter which is especially handy when working with large arrays; it helps to keep memory consumption to a minimum by allowing arrays to be reused. The only caveat is that the array has to the correct size/shape to hold the output of the function.