getting wrong answer when using arr copy() function

Viewed 38

there is an array "arr". i copied in another array "xyz". i want to update array "xyz". but getting wrong result.

metrix = [[1, 2, 2], [2, 2, 2], [2, 2, 1]]
n,m = 3,3
def package(n,m,arr):
    xyz = arr.copy()
    for i in range(n):
        for j in range(m):
            if arr[i][j] == 1:
                xyz[i][j]=0
    print("arr",arr)
    print("xyz",xyz)

package(n,m,metrix)

o/p:

arr [[0, 2, 2], [2, 2, 2], [2, 2, 0]]
xyz [[0, 2, 2], [2, 2, 2], [2, 2, 0]]

expected o/p:

arr [[1, 2, 2], [2, 2, 2], [2, 2, 1]]
xyz [[0, 2, 2], [2, 2, 2], [2, 2, 0]]
3 Answers

list.copy will return a shallow copy. For nested data structures you must use a deep copy.

from copy import deepcopy

xyz = deepcopy(arr)

This is because array.copy performs a shallow copy. Source - https://docs.python.org/3/tutorial/datastructures.html

If you only had an array of simple data types - string, number, etc, a shallow copy would have worked. But in your case, it is an array of arrays.

Use deepcopy instead.

from copy import deepcopy
arr = [ [1,2,3], [1,2,3] ]
arr_copy = deepcopy(arr)
arr_copy[0][0] = 7
print(arr)
print(arr_copy)

Output -

[[1, 2, 3], [1, 2, 3]]
[[7, 2, 3], [1, 2, 3]]
metrix = [[1, 2, 2], [2, 2, 2], [2, 2, 1]]
n,m = 3,3
def package(n,m,arr):
    xyz = [[row[i] for row in arr] for i in range(n)]
    for j in range(n):
        for i in range(m):
            if arr[i][j] == 1:
                xyz[i][j] = 0

    print("arr",arr)
    print("xyz",xyz)


package(n,m,metrix)

This works

Related