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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!