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.
Key Takeaways
- There are two ways to create an immutable Numpy array:
- By setting the writeable flag to False
- By setting the write flag to False
FAQ
- Q: Why would I want to create an immutable Numpy array?
- A: There are a few reasons why you might want to create an immutable Numpy array:
- To prevent accidental changes to the array.
- To improve performance, as immutable arrays are often faster than mutable arrays.
- To make the array thread-safe, as immutable arrays can be safely accessed by multiple threads without the risk of corruption.
- Q: What is the difference between the writeable flag and the write flag?
- The writeable flag controls whether the array can be modified. The write flag controls whether the array can be modified in-place.