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

笑着哭i 提交于 2019-12-05 17:21:29

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.

It works exactly as you have expected.

a = 2*[2*[0]]

When you multiply [[0,0]] with 2 *, both elements of the new list will point to the SAME [0,0] list. a[0] and a[1] are the same list, because the reference is copied, not the data (which would be impossible). Changing the first element of one of them changes the first element of the other.

copy.deepcopy copies the list correctly, preserving unique objects.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!