How to Create an Immutable Array in Numpy?
Immutable arrays are those arrays that cannot be modified after they are created, which means the elements of the arrays cannot be changed, or we cannot do any type of modification to the array. It remains unchanged and in read-only mode, i.e., we can only read the array but cannot change anything in the array. On the other hand, in mutable arrays, we can make desired changes to arrays, like inserting, deleting, or modifying the elements of an array. Numpy arrays are mutable. Let's look at an example of changing a NumPy array:
Code:
Output:
Explanation:
In this above code example, the array arr is created using the arrange function. Element 10 is present at the 3rd index of the array. When we change the element at this index, we get a modified array having a new value at this index. We can create NumPy arrays that are immutable using the following methods:
Using the array.flags.writeable method
Code:
Output:
Explanation:
In the above example, the array arr is created using the array method. After setting the flags.writable =False, we are setting the array in read-only mode, so when we try to change the element in the array at index 3 after setting the flag, we get a value error.
Using array.setflags (write=False) method
Code:
Output:
Explanation:
An array, arr, is created using the np.arange function. By setting setflags (write=False), we put the array in read-only mode. That's why when we try to change the element at the 3rd index of the array, the compiler produces a value error.
Conclusion
- Arrays that cannot be modified are called immutable arrays.
- Numpy arrays are mutable.
- To create immutable NumPy arrays, use array.flags.writeable=False and arr.setflags (write=False).