0

I have an 2D array called 'arr' which I copy but when I change the copy it also changes the original.
Code:

def play(arr):

    for row in range(len(arr)):
        for column in range(len(arr[row])):
            if arr[row][column] == '':
                tempArr = arr.copy()
                tempArr[row][column] = 'a'

    print(arr)

play([['', ''], ['', '']])

Output:

[['a' 'a']
 ['a' 'a']]

Expected output:

[['' '']
 ['' '']]

But this doesn't happen if in a 1D array:

def play(arr):

    for row in range(len(arr)):
            if arr[row] == '':
                tempArr = arr.copy()
                tempArr[row] = 'a'

    print(arr)
    print('Temp arr: ' + str(arr))

play(['', ''])

Output:

['' '']
tempArr: ['' 'a']

What can I do about this?

Thanks for helping!

Banjer_HD
  • 190
  • 2
  • 12
  • 1
    Possible duplicate of [A numpy array unexpectedly changes when changing another one despite being separate](https://stackoverflow.com/questions/35978165/a-numpy-array-unexpectedly-changes-when-changing-another-one-despite-being-separ) – Alexandre B. May 08 '20 at 12:31
  • @AlexandreB. Thanks for your comment but it is not a duplicate since I am already using `arr.copy()` and not using numpy arrrays – Banjer_HD May 08 '20 at 13:01

1 Answers1

1

Copy method do not recursively copy the nested structures in a list. To achieve this you need to do a deepcopy. Try this in your code :

import copy
tempArr = copy.deepcopy(arr)
manu190466
  • 1,557
  • 1
  • 9
  • 17