1

I'm making a program that requires and editable temp array that does not affect the original. However, whenever I run the function and test it, it edits the actual array like so:

x = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
y = copying(x)
y[0][0] = 1
print(x)
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

Here is the function:

def copying(array):
    temp = []

    for i in array:
        temp.append(i)        
    return temp

The function works for flat lists, but the array entry doesn't work. Is there an alternative that I should use? (I have attempted list() and copy())

waser2
  • 23
  • 1
  • 6

1 Answers1

1

You need to use the function deepcopy from copy module:

copy.deepcopy(x)

Return a deep copy of x.

This function is copying everything, even sub elements (and sub sub elements and... you understand I think). Your short example corrected:

>>> from copy import deepcopy
>>> x = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> y = deepcopy(x)
>>> y[0][0] = 1
>>> x
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> y
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
Community
  • 1
  • 1
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97