How to create an immutable Numpy array?

An immutable array is read-only, meaning you cannot modify its elements once it’s defined. 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 make the array immutable, you need to set the writable flag 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.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 you find the cumulative sum in Python?