Best practice to reduce memory usage while splitting an array
I have an array that I want to split in two halves. Due to symmetry, I'm only interested in keeping the left half of the array.
I can split the array in half by saying:
[a,b] = numpy.split(c,2)
where c is also an array.
Is there a way to return array 'a' or alternatively remove array "b" from memory immediately after splitting the array?
source to share
You can copy the first half with
a = x[len(x)//2:].copy()
this would allocate a copy and move the content (thus temporarily takes 1.5 times more memory)
Otherwise, you can just say
a = x[len(x)//2:]
to get a reference to the first half, but the other part will not be removed from memory
source to share
I'm not sure, but I think it might be better because it relies on the implementation list
( docs ) and I'm sure everything was correct:
>>> r = range(10)
>>> r
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del r[5:]
>>> r
[0, 1, 2, 3, 4]
See also the del statement for lists .
source to share