Let’s check how to create an immutable Numpy array.
Setting writeable flag
To make the array immutable, you need to set the writeable flag to false.
import numpy as np my_array = np.array([1, 2, 3]) print(my_array) my_array[1] = 5 print(my_array) my_array.flags.writeable = False my_array[2] = 6 print(my_array)
As you can see, it is not possible to change the array. Python displays assignment destination is a read-only ValueError.
Traceback (most recent call last): File "C:\Users\pythoneo\PycharmProjects\pythoneoProject\immutable_array_python.py", line 11, inmy_array[2] = 6 ValueError: assignment destination is read-only
Setting a writeable flag rendered your code immutable.To turn off read-only mode, you need to set the writeable flag back to true.
Setting write flag
Alternatively, you can set the write flag to false.
import numpy as np my_array = np.array([1, 2, 3]) print(my_array) my_array[1] = 5 print(my_array) my_array.setflags(write=False) my_array[2] = 6 print(my_array)
Python displays ValueError as well. The full error message is as follows:
Traceback (most recent call last): File "C:\Users\pythoneo\PycharmProjects\pythoneoProject\immutable_array_python.py", line 11, inmy_array[2] = 6 ValueError: assignment destination is read-only
Set the write flag back to true to allow editing.