Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does memory allocation work in python in this case?

Suppose I have a very large numpy array a, and I want to add the numerical value 1 to each element of the array. From what I have read so far:

a += 1 

is a good way of doing it rather than:

a = a + 1

since in the second case a new array a is created in a different memory slot, while in the first case the old array is effectively replaced in the same memory slot.

Suppose I want to do the following instead:

a = 1-a

What would be the memory efficient way of doing the above?

like image 661
konstant Avatar asked Dec 20 '25 17:12

konstant


2 Answers

numpy.subtract(1, a, out=a)

Using the subtract ufunc directly gives you more control than the - operator. Here, we use the out parameter to place the results of the subtraction back into a.

like image 141
user2357112 supports Monica Avatar answered Dec 23 '25 07:12

user2357112 supports Monica


You could do it in place like so:

a *= -1
a += 1
like image 36
Julien Avatar answered Dec 23 '25 07:12

Julien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!