Banjer_HD
Banjer_HD

Reputation: 300

Python copy of array also changes normal array

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!

Upvotes: 0

Views: 69

Answers (1)

manu190466
manu190466

Reputation: 1603

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)

Upvotes: 1

Related Questions