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!

2

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.