Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deepcopy on nested referenced lists created by list multiplication does not work

As much as I love Python, the reference and deepcopy stuff sometimes freaks me out.

Why does deepcopy 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 am using a numpy array as a workarround which I need later on anyway. But I really had hoped that if I used deepcopy I would not have to chase any unintended references any more. Are there any more traps where it does not work?

like image 765
Gonzo Avatar asked Feb 01 '11 17:02

Gonzo


1 Answers

It doesn't work because you are creating an array with two references to the same array.

An alternative approach is:

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

Or the more explicit:

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

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

Are there any more traps where it does not work?

Any time you have an array containing references you should be careful. For example [Foo()] * 2 is not the same as [Foo() for i in range(2)]. In the first case only one object is constructed and the array contains two references to it. In the second case, two separate objects are constructed.

like image 71
Mark Byers Avatar answered Oct 12 '22 22:10

Mark Byers