Help me to understand python code related to numpy library?

python

#1

Hi,

I am new to python. Recently I have started exploring Numpy library. In below code I have created an array (ar) and also created another array(new_ar) using slicing method but whenever I do change in the new_ar array, this change also reflect in the original array “ar” also. Is slicing create a link between these two? if yes please help me with the methods to create copy not link.

Code:

ar=np.arange(12)
new_ar=ar[2:5:]
new_ar[1]=25
ar

Output:

  array([ 0,  1,  2, 25,  4,  5,  6,  7,  8,  9, 10, 11])

Thanks,
Satish


#2

Satish,

If you simply assign a list to a new variable in Python, it will create a reference and will continue to make changes to the initial reference.

If you want to copy all the elements and create a new list, you can use copy.deepcopy function

import copy
new_ar=copy.deepcopy(ar[2:5])

Hope this helps.

Kunal