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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With