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.
Build an AI-First Career, Master the Complete Skillset
Choose from our industry-leading programs designed for career success
Modern Software and AI Engineering Program
Master full-stack development with AI integration
+1000 moreModern Data Science and ML with specialisation in AI
Advanced data science techniques with AI specialization
+1000 moreAdvanced AIML with Specialisation in Agentic AI
Deep dive into AIML with focus on Agentic systems
+1000 moreDevOps, Cloud & AI Platform Engineering
Build and manage AI-powered cloud infrastructure
+1000 moreAI Engineering Advanced Certification by IIT-Roorkee
Premier AI engineering certification from IIT-Roorkee
AI Forward Deployed Engineer Program
Full-stack engineering, production AI and client-facing consulting
+1000 moreConclusion
- 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).