Deepcopy for nested link lists created by multiplying lists does not work

As much as I love Python, the reference and deep copy technique sometimes leads me out.

Why deepcopy does not work here:

>>> import copy
>>> a = 2*[2*[0]]
>>> a
[[0, 0], [0, 0]]
>>> b = copy.deepcopy(a)
>>> b[0][0] = 1
>>> b
[[1, 0], [1, 0]]     #should be: [[1, 0], [0, 1]]
>>> 

I use the numpy array as the desktop that I need later. But I really hoped that if I used a deep copy, I would no longer have to chase any inadvertent links. Are there more traps where it doesn't work?

+3
source share
2 answers

This does not work because you are creating an array with two references to the same array.

Alternative approach:

[[0]*2 for i in range(2)]

Or more explicit:

[[0 for j in range(2)] for i in range(2)]

This works because it creates a new array at each iteration.

, ?

, , , . , [Foo()] * 2 [Foo() for i in range(2)]. , . .

+10

, .

a = 2 * [2 * [0]]

[[0,0]] 2 * SAME [0,0]. a[0] a[1] - , , ( ). .

copy.deepcopy , .

+7

Source: https://habr.com/ru/post/1789287/


All Articles