How to Create an Immutable Array in Numpy?

Learn via video courses
Topics Covered

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.

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

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).