How to Create Immutable NumPy Array (Set flags.writeable=False or setflags(write=False))

An immutable NumPy array is read-only, preventing element modifications after setting the writeable flag to False for data integrity protection. This can be useful when you want to ensure data integrity or prevent accidental changes to the array.

Numpy immutable array

Setting writeable flag

To create an immutable NumPy array using writeable flag, set array.flags.writeable = False or use array.setflags(write=False)—both trigger ValueError on modification attempts.

import numpy as np

my_array = np.array([1, 2, 3])
print(my_array)

my_array[1] = 5
print(my_array)

my_array.flags.writeable = False

my_array[2] = 6
print(my_array)

As demonstrated, attempting to modify the array after setting the writable flag to False results in a Python ValueError, indicating the array is read-only.

Traceback (most recent call last):
  File "C:\Users\pythoneo\PycharmProjects\pythoneoProject\immutable_array_python.py", line 11, in 
    my_array[2] = 6
ValueError: assignment destination is read-only

Setting a writeable flag rendered your code immutable. To turn off read-only mode, you need to set the writeable flag back to true.

Setting the write flag

Alternatively, you can use the setflags method to make the array immutable by setting write to False.

import numpy as np

my_array = np.array([1, 2, 3])
print(my_array)

my_array[1] = 5
print(my_array)

my_array.setflags(write=False)

my_array[2] = 6
print(my_array)

Python displays ValueError as well. The full error message is as follows:

Traceback (most recent call last):
  File "C:\Users\pythoneo\PycharmProjects\pythoneoProject\immutable_array_python.py", line 11, in 
    my_array[2] = 6
ValueError: assignment destination is read-only

Set the write flag back to true to allow editing.

By creating an immutable NumPy array, you can ensure data consistency and prevent unintended modifications, making it a valuable tool for various data manipulation and analysis tasks in Python.

See also  How to generate random matrix in Numpy?