With the following code, I iterate over an array in reverse order and print and pop the last item. In the end I expect to see an empty array, but it is not empty.
a = array([5,1,2,4,9,2]).reshape(-1, 1)
for j in a[::-1]:
print(j.item())
np.delete(a, len(a)-1, 0)
print("a=", a)
Output is
2
9
4
2
1
5
a= [[5]
[1]
[2]
[4]
[9]
[2]]
How can I fix that? With the syntax of delete(array, pos, axis), I expect to delete the rows from last to start.
>Solution :
numpy.delete does not work in place:
>>> np.delete(a, len(a)-1, 0)
array([[5],
[1],
[2],
[4],
[9]])
I am not sure why you would want to iterate over an array this way but you would need:
a = np.array([5,1,2,4,9,2]).reshape(-1, 1)
for j in a[::-1]:
print(j.item())
a = np.delete(a, len(a)-1, 0) ## assign back to a
print("a=", a)
output:
2
9
4
2
1
5
a= []