Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does modifying copy of array affect original?

Tags:

python

list

Hi everyone I am sorry if this is a noob question but I am using python and I have an issue where I copy an array but then when I modify the copy it affects the original. I want to add a linear offset from the boundaries matrix to a set of coordinates:

boundaries = [[5.818, 0.0, 0.0], [0.0, 5.818, 0.0], [0.0, 0.0, 5.818]]

xyzCoord = [[0.0, 0.0, 0.0], [2.909, 2.909, 0.0], ...

extraX=[]
for i in range(0,len(xyzCoord)):
    toAdd=[]
    toAdd=xyzCoord[i]
    toAdd[0]=toAdd[0]+boundaries[0][0]

print xyzCoord

The output I expect is that xyzCoord should not be affected because I make a duplicate (toAdd) and then modify that. Strangely enough this loop does affect my xyzCoord:

The output is:

[[5.818, 0.0, 0.0], [0.0, 5.818, 0.0], [0.0, 0.0, 5.818]]

[[0.0, 0.0, 0.0], [2.909, 2.909, 0.0], ...

[[5.818, 0.0, 0.0], [8.727, 2.909, 0.0], ...

EDIT: For context, the idea is that I want to eventually make a separate list with the transposed values and then ultimately create an intercalated list but this part is holding me up. I.e. I would ideally like to create: [[0.0, 0.0, 0.0], [5.818, 0.0, 0.0], [2.909, 0.0, 0.0], [8.727, 2.909, 0.0]...] and then make a larger loop for Y and Z. This way I could propagate some coordinates in the X Y and Z and arbitrary number of times.

like image 383
Coherent Avatar asked Jan 14 '23 19:01

Coherent


2 Answers

This is one of the most surprising things about Python - the = operator never makes a copy of anything! It simply attaches a new name to an existing object.

If you want to make a copy of a list, you can use a slice of the list; the slicing operator does make a copy.

toAdd=xyzCoord[i][:]

You can also use copy or deepcopy from the copy module to make a copy of an object.

like image 81
Mark Ransom Avatar answered Jan 28 '23 16:01

Mark Ransom


toAdd is not a duplicate. The following makes toAdd refer to the same sub-list as xyzCoord[i]:

toAdd = xyzCoord[i]

When you change elements of toAdd, the corresponding elements of xyzCoord[i] also change.

Instead of the above, write:

toAdd = xyzCoord[i][:]

This will make a (shallow) copy.

like image 21
NPE Avatar answered Jan 28 '23 18:01

NPE