2

I created 2d list, then copied it and change first element of a copy with f2 function. But somehow original list changes too. But I think that created copy by value, it's not referenced to the parent. How can I change copy list and do not change original?

def f2(m):
    m[0][0] = 99

k = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
m = k[:][:] #[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print(k)
f2(k)
print(m)
mike
  • 37
  • 4

2 Answers2

2

k[:][:] doesn't create a deep copy of the list k. That's why changing the values in m is changing the values in k as well. You can use python deepcopy instead :

from copy import deepcopy
m = deepcopy(k)

As mentioned in the python docs :

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Read more about deepcopy and shallow copy here

Community
  • 1
  • 1
Ashish Ranjan
  • 5,523
  • 2
  • 18
  • 39
0

The line m = k[:][:] does not create a deep-copy of the list. It just creates a shallow copy with the first [:] and then creates another shallow copy of that shallow copy with the second [:].

Try m = [x[:] for x in k] instead.

tobias_k
  • 81,265
  • 12
  • 120
  • 179