Why isn't the final value of the numpy array npary in the following code the
same as the initial value before some but not all elements of the array were
changed to a new value?

I know I am missing something basic here.  I thought I understood the
concepts of immutable vs mutable values but obviously I missed something.

My environment is Win10-64, Python 3.8.5, numpy 1.19.2.

Code and output follows.  TIA for any help you can provide to cure my
ignorance.

Peter

--- nptest.py ---
import numpy as np
import sys

if len(sys.argv) > 0:
    try:
        asz = int(sys.argv[1]) + 0
    except:
        asz = 4

npary = np.full([asz, asz, asz], 0, dtype=np.int32)
print("Array before change=\n{}".format(npary))
svary = npary[:, :, :]
npary[1:-1, 1:-1, 1:-1] = 1
print("Array after change=\n{}".format(npary))
npary = svary[:, :, :]
print("Array after restore=\n{}".format(npary))
--- nptest.py ---

--- output ---
Array before change=
[[[0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]]

 [[0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]]

 [[0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]]

 [[0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]]]
Array after change=
[[[0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]]

 [[0 0 0 0]
  [0 1 1 0]
  [0 1 1 0]
  [0 0 0 0]]

 [[0 0 0 0]
  [0 1 1 0]
  [0 1 1 0]
  [0 0 0 0]]

 [[0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]]]
Array after restore=
[[[0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]]

 [[0 0 0 0]
  [0 1 1 0]
  [0 1 1 0]
  [0 0 0 0]]

 [[0 0 0 0]
  [0 1 1 0]
  [0 1 1 0]
  [0 0 0 0]]

 [[0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]]]
--- output ---


-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to