VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-make-a-numpy-array-read-only/

⇱ How to make a NumPy array read-only? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to make a NumPy array read-only?

Last Updated : 4 Nov, 2022

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 writable flag of the NumPy array to false.

Syntax:

array.flags.writable=False

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

Example:

Output:

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 "gfg9.py", line 11, in <module>
 a[1]=7
ValueError: assignment destination is read-only
Comment