A Numpy caveat when referencing elements of an array

Numpy
Python
Author
Published

February 23, 2024

Modified

March 10, 2024

Understanding when a view or copy for a Numpy array is returned is important, or else the array may be modified in place by mistake. An example below:

import numpy as np

print("Numpy version: ", np.__version__)


def print_result(test_array):
    a = test_array.copy()
    b = a[0]
    b += 1
    print(
        f'b = a[0], {"unchanged" if np.allclose(a, test_array) else "changed"}',
    )

    a = test_array.copy()
    b = a[[0]]
    b += 1
    print(
        f'b = a[[0]], {"unchanged" if np.allclose(a, test_array) else "changed"}',
    )

    a = test_array.copy()
    b = a[0:1]
    b += 1
    print(
        f'b = a[0:1], {"unchanged" if np.allclose(a, test_array) else "changed"}',
    )


print("For 1D array:")
print_result(np.zeros(2))
print("-" * 10)
print("For 2D array:")
print_result(np.zeros((2, 2)))
Numpy version:  1.23.1
For 1D array:
b = a[0], unchanged
b = a[[0]], unchanged
b = a[0:1], changed
----------
For 2D array:
b = a[0], changed
b = a[[0]], unchanged
b = a[0:1], changed

Note that the result is different for 1D or 2D Numpy arrays.

For more, check Numpy docs Copies and views.

Reuse

Citation

BibTeX citation:
@online{li2024,
  author = {Li, Chengkun},
  title = {A {Numpy} Caveat When Referencing Elements of an Array},
  date = {2024-02-23},
  url = {https://pipme.github.io/posts/2024-02-23-Numpy-caveat/index-gist.html},
  langid = {en}
}
For attribution, please cite this work as:
Li, Chengkun. 2024. “A Numpy Caveat When Referencing Elements of an Array.” February 23, 2024. https://pipme.github.io/posts/2024-02-23-Numpy-caveat/index-gist.html.