NumPy arrays can be made immutable, meaning that their values cannot be changed after they are created. This can be useful in situations where you want to ensure that your data remains constant throughout your program, or where you want to avoid accidentally modifying your data. In this thread, we will cover two techniques that help us in making an immutable array.
1. Using "setflags()" function :
The setflags()
method is one way to make a NumPy array immutable. The code you provided sets the write flag to False for the array, which makes it read-only.
In the above code, we first import the NumPy library and assign it the alias np
. We create an array by using np.array()
method. After that, we apply setflags()
function with parameter write=False
, which makes an array immutable.
Note: The above code raises a ValueError , which shows array can’t be modified.
2. Using "flags.writeable" attribute:
To make an array immutable in NumPy, you can use the flags.writeable
attribute to set the array to read-only mode. This attribute is a Boolean value that indicates whether the array can be modified or not.
In the above code, we first import the NumPy library and assign it the alias np
. We use np.array()
function to create the array and then we set flags.writeable
attribute to False
which makes an array immutable.
Note: The above code raises a ValueError , which shows array can’t be modified.