问题
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