Unexpected update result on the quickly nested list in Python [duplicate]

一世执手 提交于 2020-01-30 12:04:47

问题


Why couldn't the first element but the whole column be updated below?

>>> x=2*[2*[1]]
>>> x
[[1, 1], [1, 1]]
>>> x[0][0]=2
>>> x
[[2, 1], [2, 1]]

回答1:


Even tho this is a clear duplicate but use range:

>>> x=[[1 for i in range(2)] for x in range(2)]
>>> x
[[1, 1], [1, 1]]
>>> x[0][0]=2
>>> x
[[2, 1], [1, 1]]
>>> 

At least still able to do:

>>> x=[[1]*2 for x in range(2)]
>>> x[0][0]=2
>>> x
[[2, 1], [1, 1]]
>>> 


来源:https://stackoverflow.com/questions/52175690/unexpected-update-result-on-the-quickly-nested-list-in-python

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