Skip to content
Related Articles

Related Articles

How to make a NumPy array read-only?
  • Last Updated : 29 Aug, 2020

Let’s discuss how to make NumPy array immutable i.e that can not be rewritten or can’t be changed. This can be done by setting a writeable flag of the NumPy array to false.



 This set the writable flag to false and hence array becomes immutable i.e read-only. See the example below



import numpy as np
a = np.zeros(11)
print("Before any change ")
a[1] = 2
print("Before after first change ")
a.flags.writeable = False
print("After making array immutable on attempting  second change ")
a[1] = 7


Before any change
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
Before after first change
[0. 2. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
After making array immutable on attempting  second change
Traceback (most recent call last):
  File "", line 11, in <module>
ValueError: assignment destination is read-only

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :