Why does modifying copy of array affect original?

后端 未结 3 1495
情书的邮戳
情书的邮戳 2020-12-18 09:21

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

相关标签:
3条回答
  • 2020-12-18 09:31

    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.

    0 讨论(0)
  • 2020-12-18 09:35

    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.

    0 讨论(0)
  • 2020-12-18 09:39

    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.

    0 讨论(0)
提交回复
热议问题