Python array strange behavior? [duplicate]

余生长醉 提交于 2019-12-20 04:32:24

问题


Can anyone explain why is this happening?

Case 1:

>>> a = [[0]] *3
>>> print a
[[0], [0], [0]]
>>> a[1].append(0)
>>> print a
[[0, 0], [0, 0], [0, 0]]

Case 2:

>>> a = [[0],[0],[0]]
>>> print a
[[0], [0], [0]]
>>> a[1].append(0)
>>> print a
[[0], [0, 0], [0]]

Why is this going on? I am expecting that the behavior of the array in case 1 to be as in case 2 but it is not for some reason.


回答1:


In the first case, you are creating a list [0] and duplicate it 3 times. This is the same object repeated three times. You should use the star form only with immutable type

To avoid this issue when you have a mutable type, use list comprehension:

a = [[0] for _ in range(3)]



回答2:


In the first case, the three elements in a actually reference to the same list objects. You can check their id:

>>> id(a[0])
4524132472
>>> id(a[1])
4524132472
>>> id(a[2])
4524132472


来源:https://stackoverflow.com/questions/38017963/python-array-strange-behavior

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