python nested list unexpected behaviour [duplicate]

醉酒当歌 提交于 2019-12-13 10:23:08

问题


I've ran into an unexpected behavior when using a nested list in python, that took a while to debug. If a list is initialized like this:

a = [[None] * 2] * 2
a
[[None, None], [None, None]]

and another list initialized like this:

b = [[None, None], [None, None]]
b
[[None, None], [None, None]]

I would expect the same behavior from both these lists, but if I do:

a[0][0] = 3
a
[[3, None], [3, None]]

and if I do:

b[0][0] = 3
b
[[3, None], [None, None]]

Can someone explain the reason why this happens? thanks


回答1:


>>> a = [[None] * 2] * 2
>>> id(a[0])
41554168
>>> id(a[1])
41554168
>>> b = [[None, None], [None, None]]
>>> id(b[0])
41549576
>>> id(b[1])
41557368

This should explain



来源:https://stackoverflow.com/questions/35421624/python-nested-list-unexpected-behaviour

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