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:
Python
import numpy as np a = np.zeros( 11 ) print ( "Before any change " ) print (a) a[ 1 ] = 2 print ( "Before after first change " ) print (a) a.setflags(write = False ) print ( "After making array immutable on attempting second change " ) a[ 1 ] = 7 |
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