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.
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.
You can also use
copy
ordeepcopy
from thecopy
module to make a copy of an object.Because your using an array of arrays (list of lists) the inner list is an object so you are only copying the reference of the inner object instead of copying the values.
toAdd
is not a duplicate. The following makestoAdd
refer to the same sub-list asxyzCoord[i]
:When you change elements of
toAdd
, the corresponding elements ofxyzCoord[i]
also change.Instead of the above, write:
This will make a (shallow) copy.